Javascript String.replace with dynamic regular expressions?

前端 未结 4 1353
清酒与你
清酒与你 2020-12-30 22:50

I have the following code, which works, but I need to inject some different stuff into the regular expression object (regex2) at runtime. However, text.replace

4条回答
  •  轮回少年
    2020-12-30 23:56

    Addition to CMS: The RegExp constructor has an second optional parameter flags
    (15.10.4 The RegExp Constructor)

    var text = "This is a Test.";
    
    var myRegExp = new RegExp('teST','i');
    
    text.replace(myRegExp,'Example');
    // -> "This is a Example."
    

    as Flags you can set

    • g -> global search (all occurrences)
    • i -> case insensitive
    • m -> multiline

提交回复
热议问题