Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Passing a function with matches to replace( regex, func(arg) ) doesn't work

Tags:

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' , "g")

so be careful!

like image 812
Lorenz Lo Sauer Avatar asked Aug 25 '11 14:08

Lorenz Lo Sauer


1 Answers

$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" 
like image 79
Joe Avatar answered Sep 19 '22 06:09

Joe