Javascript: Passing a function with matches to replace( regex, func(arg) ) doesn't work
According to this site the following replace method should work, though I am sceptical. http://www.bennadel.com/blog/55-Using-Methods-in-Javascript-Replace-Method.htm
My code is as follows:
text = text.replace(
new Regex(...),
match($1) //$.. any match argument passed to the userfunction 'match',
// which itself invokes a userfunction
);
I am using Chrome 14, and do not get passed any parameters passed to the function match?
Update:
It works when using
text.replace( /.../g, myfunc($1) );
The JavaScript interpreter expects a closure, - apparent userfunctions seem to lead to scope issues i.e. further userfunctions will not be invoked. Initially I wanted to avoid closures to prevent necessary memory consumption, but there are already safeguards.
To pass the arguments to your own function do it like this (wherein the argument[0] will contain the entire match:
result= text.replace(reg , function (){
return wrapper(arguments[0]);
});
Additionally I had a problem in the string-escaping and thus the RegEx expression, as follows:
/\s......\s/g
is not the same as
new Regex ("\s......\s" , "g")
or
new Regex ('\s......\s'开发者_JS百科 , "g")
so be careful!
$1 must be inside the string:
"string".replace(/st(ring)/, "gold $1")
// output -> "gold ring"
with a function:
"string".replace(/st(ring)/, function (match, capture) {
return "gold " + capture + "|" + match;
});
// output -> "gold ring|string"
I think you're looking for new RegExp(pattern, modifiers).
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
精彩评论