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")
ornew Regex ('\s......\s' , "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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With