JavaScript replace/regex

后端 未结 3 518
囚心锁ツ
囚心锁ツ 2020-11-27 14:02

Given this function:

function Repeater(template) {

    var repeater = {

        markup: template,

        replace: function(pattern, value) {
                     


        
3条回答
  •  清酒与你
    2020-11-27 14:07

    You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):

      "$TESTONE $TESTONE".replace( new RegExp("\\$TESTONE","gm"),"foo")
    

    Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).

    Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.

提交回复
热议问题