If you ask for an example of String.prototype.replace in JavaScript, the most common response would be:

1 2 var str = 'foobar' ; var replaced = str . replace ( 'bar' , 'baz' );

or

1 2 var str = 'The quick brown fox had a great Xmas' ; var replace = str . replace ( /Xmas/i , 'Christmas!' );

So it's mostly about seach and replace feature that most (P.S: By most of them I mean those I have come across on IRC.) of them wouldn talk about but would have not noticed that the signature of the replace method is like:

1 replace ( regexp | substr , newSubStr | function [, flags ])

From the signature, the focus of this post will be on the function in the params, this will be invoked to create the new substring and receives the below parameters:

match : The matched substring.

p1,p2..pn : The nth parenthesized submatch string.

offset : The offset of the matched substring.

string: The entire string which is being processed.

Let us see few example application of the same:

A simple example of increasing your protein and fat intake ;)

1 2 3 > function replacer ( match ) { return 2 * match } > '10 gms of protein and 5gms of fat.' . replace ( /[0-9]+/g , replacer ) > '20gms of protein and 10gms of fat.'

The below snippet replaces a Fahrenheit degree with its equivalent Celsius degree, for an input 212F , the function returns 100C , nothing big about this, but if you notice that the replace function's second agrument is a function convert which receives the parameters specified in the table above and returns a string.

1 2 3 4 5 6 7 8 9 10 // from mdn function f2c ( temprature ) { function convert ( match , p1 , offset , string ) { return (( p1 - 32 ) * 5 / 9 ) + 'C' ; } var s = String ( temprature ); var test = /(-?\d+(?:\.\d*)?)F\b/g ; return s . replace ( test , convert ); }

This feature would be more useful when you are doing a replace operation over a loop, using a replacer function like this one could totally avoid a loop.

Say, the input is an string that looks like:

1 let str = '___.___.___.__._...__' ;

Where __. is a high singal and __. is a low singal and rest of them are noise, you can filter them easily with an explicity loop using the replacer function like:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 let str = '___.___.___.__._...__' ; let res = []; str . replace ( /(___.)|(__.)/g , function ( match , p1 , p2 ) { if ( p1 ) { res . push ({ high : true , length : p1 . length }); } if ( p2 ) { res . push ({ high : false , length : 1 }); } }); console . log ( res ); /* [ { high: true, length: 4 }, { high: true, length: 4 }, { high: true, length: 4 }, { high: false, length: 1 } ] */

Well, it has been a decent amount of time since I wrote amount some fundamentals of JavaScript, hope this was useful for you, feel free to share few of your experince with replacer functions.