Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-Browser Regular expression library for Javascript to replace using function

Is there a library for replacing using functions as argument

when I call this function

"foo[10]bar[20]baz".replacef(/\[([0-9]*)\]/g, function(a) {
    return '[' + (ParseInt(a)*10) + ']';
});

it should return

"foo[20]bar[30]baz";

and when I call with this

"foo[10;5]bar[15;5]baz".replacef(/\[([0-9]*);([0-9]*)\]/g, function(a, b) {
    return '_' + (ParseInt(a)+ParseInt(b)) + '_';
});

it should return

"foo_15_bar_20_baz"

Is there existing Cross-Browser library that have function like this or similar in JavaScript?

like image 981
jcubic Avatar asked May 23 '26 18:05

jcubic


2 Answers

That's how the "replace()" function already works. If the second parameter is a function, it's passed a list of arguments that are pretty much the same as the array returned from the RegExp "exec()" function. The function returns what it wants the matched region to be replaced with.

The first argument to the called function is the whole matched string. The second and subsequent arguments are the captured groups from the regex (like your second example). Your second example, however, would need a function with one more parameter to hold the entire matched string.

Example:

var s = "hello world".replace(/(\w+)\s*(\w+)/, function(wholeMatch, firstWord, secondWord) {
  return "first: " + firstWord + " second: " + secondWord;
});
alert(s); // "first: hello second: world"
like image 119
Pointy Avatar answered May 25 '26 08:05

Pointy


As far as I know you can readily do something like this in javascript :

"foo[10]bar[20]baz".replace(/\[([0-9]+)\]/g, function() {
  return '[' + (parseInt(arguments[1])*10) + ']';
});

This is afaik cross browser (notice that parseInt got no leading uppercase p), arguments contains the match, index 0 is the whole thing, 1 and so on are the captured groups.

like image 28
yent Avatar answered May 25 '26 08:05

yent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!