JavaScript replace() String

The replace() function searches through a given string looking for a substring or regular expression and replaces it with a new substring.

Syntax

str.replace(substr_or_regexp,replace_with);
str = string you want to search through
Parameter Required Description
substr_or_regexp Yes a substring or regular expression that you want to replace
replace_with Yes string you want to replace matching above parameter

How to Use it

To use the replace() function, first create a variable for a string you want to search through and replace something within. For example:
var anyNameYouLike = 'some sort of text/string right here';
Next you want to first type the variable refernce to the string (in this case it's anyNameYouLike) then a period. The period is called a concatenation - which is just a fancy word meaning to join two things. The period here tells the browser (which renders the JavaScript) that what ever follows the period should be referneced to the string variable to the left of the period.
Now imediatly following the period is the replace() function. Then within the replace function add in 2 parameters seperated by a comma. The definations of the parameters are under the syntax section above.
Basically the first parameter is what you want to find and replace and the seconds one is what to replace it with. So the final code would be as follows.
var anyNameYouLike = 'some sort of text/string right here';
anyNameYouLike.replace('right','in');
The results would be a string as follows
some sort of text/string in here
The search is case sensativity and only replaces the first matching string, but case-insensitive and replacing all matching strings can also be done. See those examples in the example section below for detail.

Browser Support

Desktop Browsers:
  • firefox
    Firefox
  • ie
    Internet Explorer
  • chrome
    Chrome
  • safari
    Safari
  • opera
    Opera
Mobile Browsers:
  • android
    Android
  • iphone
    iPhone/iPad
The replace() function is supported in all major browsers.

Examples

Example 1 (standard)

var str = 'Mary had a little lamb.';
str = str.replace('lamb','dog');
Results:
str = 'Mary had a little dog.';

Example 2 (standard)

var str = 'Good dog, good dog.';
str = str.replace('Good','Bad');
Results:
str = 'Bad dog, good dog.';

Example 3 (case-insensitive)

var str = 'ALL CAPS.';
str = str.replace(/caps/i,'lower-case');
Results:
str = 'ALL lower-case.';

Example 4 (replace all)

var str = 'Good dog. Good dog.';
str = str.replace(/Good/g,'Bad');
Results:
str = 'Bad dog. Bad dog.';

Example 5 (replace all, case-insensitive)

var str = 'GOOD dog. GOOD dog.';
str = str.replace(/good/ig,'Bad');
Results:
str = 'Bad dog. Bad dog.';