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"
开发者_StackOverflow中文版Is there existing Cross-Browser library that have function like this or similar in JavaScript?
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"
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.
精彩评论