Search and Replace in JavaScript Strings
The JavaScript string replace
method returns a new string resulting from a search and replace operation on the string it is invoked on. The first argument to the replace
method is what you are searching for, expressed either as a string or a regular expression. The second argument is what you will replace it with. The second argument can be a string, or a function that returns the replacement string.
If the first argument is a regular expression, the global modifier can be included for a global search and replace. Otherwise only the first instance will be replaced.
Our first example specifies the first argument as a string:
var str = 'My favorite scripting language is PHP.';
var str2 = str.replace('PHP', 'JavaScript');
console.log( str2 );
// My favorite scripting language is JavaScript.
The next example specifies the first argument as a regular expression with the global modifier included:
var str = 'My favorite scripting language is PHP. That\'s right, PHP!';
var str2 = str.replace(/PHP/g, 'JavaScript');
console.log( str2 );
// My favorite scripting language is JavaScript. That's right, JavaScript!
A Function as a Replacement Argument
A function can be used to supply the replacement text for the replace
method. It can accept the following arguments: the match, the matches for parenthesized sub-expressions, the index location in the string of the match, and the string being searched. The following demonstrates a simple example:
var str = 'I love kittens. I love puppies too.';
var re = /love/g;
var str2 = str.replace(re, function(match) { return match.toUpperCase(); });
console.log( str2 ); // I LOVE kittens. I LOVE puppies too.
Replacement String Patterns
A dollar sign can be used in the replacement string to signify particular patterns. For example, $&
refers to the match itself, and $1
refers to the first parenthesized sub-expression. The following demonstrates how these can be used:
var str = 'I love JavaScript!';
var re = /love/;
var str2 = str.replace(re, '***$&***');
console.log( str2 ); // I ***love*** JavaScript!
var str = 'Great Blessing';
var re = /(\w+)\s(\w+)/g;
var str2 = str.replace(re, 'A $2 So $1!');
console.log( str2 ); // A Blessing So Great!
MDN's entry on the replace method provides more information and examples for the replacement function and string patterns. They also cover the new replaceAll method.