JavaScript: the replace() function

The replace() function is a string utility function that belongs to the String object. This means that this function can be used on any string. However, this function is more powerful than you can imagine. Its purpose is to replace a portion of a string with a given string. Usually this function is used in this way:

var str = 'Foo';
var newStr = str.replace('F', 'B');
alert(newStr); // 'Boo'

In this case, the letter 'F' has been replaced with 'B'. However, this function also accepts a regular expression as its first parameter. If you use this feature, bear in mind that you have to set the flag g on the regular expression to allow the search to be performed on the entire string without stopping at the first match:

var str = '123abc456';
var newStr = str.replace(/\d+/g, '');
alert(newStr); // 'abc'

You can even use the matching groups of regular expression to keep the matches and add new strings as well:

var str = '123abc456';
var newStr = str.replace(/\d+/g, 'n$1');
alert(newStr); // 'n1n2n3abcn4n5n6';

Finally, this function also accepts a callback function to perform additional replacements on your string.

Leave a Reply

Note: Only a member of this blog may post a comment.