[removed] Passing a function with matches to replace( regex, func(arg) ) doesn't work

后端 未结 2 1435
孤城傲影
孤城傲影 2020-12-29 07:40

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

<
相关标签:
2条回答
  • 2020-12-29 08:29

    I think you're looking for new RegExp(pattern, modifiers).

    http://www.w3schools.com/jsref/jsref_obj_regexp.asp

    0 讨论(0)
  • 2020-12-29 08:36

    $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"
    
    0 讨论(0)
提交回复
热议问题