Is there something like PHP preg_replace_callback () in javascript?

What I want to do is str.replace(pattern, callback) ,

not just str.replace(pattern, replace_pattern) ,

Can this be done in javascript?

+6
javascript regex
source share
2 answers

Why, yes, you can do just that: str.replace(pattern, function () { ... }) .

Here is some documentation: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace

+12
source share

Yes

 var s2 = s1.replace(/regex/, function(whole, part1, part2, ...) { ... }) 

The function is passed in the entire matched string as the first argument. If there are capture groups, they are passed as subsequent arguments.

+5
source share

All Articles