If you ask for an example of String.prototype.replace
in JavaScript, the most common response would be:
1 2 |
|
or
1 2 |
|
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
|
|
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 |
|
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 |
|
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
|
|
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 |
|
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.