Replace () as call back function

We know that the replace() method will return a new string based on the pattern and its corresponding replacement argument.

Here the pattern can be either general string or regular expression that we normally use. And for replacement argument in most cases we use string as replacement. But there is an extensible facility to use this replacement as call back function.

Here we go with a small example code snippets.

Code Snippets:


var numbers = '34 55 27 45 72',
type1 = numbers.replace(/\d+/g, '*'),
type2 = numbers.replace(/\d+/g, function (item) {
return +item < 50 ? '*' : item;
});
console.log("simple replace() : ", type1);
console.log("replace() with call back function : ", type2);

Fiddle Demo

Note:

The call back function will be invoked for the each matched set of an item, when the first parameter regular expression is declared as global.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s