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

27,807

$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"
Share:
27,807
Lorenz Lo Sauer
Author by

Lorenz Lo Sauer

A desire to craft. An enthusiast of "difficult". A passion for people, technology and processes. How can I assist you today? Thanks to everyone who contributes and shares knowledge here in StackOverflow and StackExchange. Links: personal website about.me Blog @sauerlo Google+ Code Snippets Github CodeProject

Updated on May 18, 2020

Comments

  • Lorenz Lo Sauer
    Lorenz Lo Sauer about 4 years

    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!

  • Lorenz Lo Sauer
    Lorenz Lo Sauer almost 13 years
    yes, in the string $1 is parsed by the replace function. In the code example $1 is just any variable, taken from the example in the link. --- It is best to pass arguments[0] though, because the last argument will contain the entire text.
  • Twisty
    Twisty about 8 years
    Took a bit to wrap my head around, but exactly what I needed.
  • Abby Chau Yu Hoi
    Abby Chau Yu Hoi about 3 years
    modifiers are sufficient for his case.