JS replacing all occurrences of string using variable

This question already has an answer here:

  • How do you use a variable in a regular expression? 16 answers

  • The RegExp constructor takes a string and creates a regular expression out of it.

    function name(str,replaceWhat,replaceTo){
        var re = new RegExp(replaceWhat, 'g');
        return str.replace(re,replaceTo);
    }
    

    If replaceWhat might contain characters that are special in regular expressions, you can do:

    function name(str,replaceWhat,replaceTo){
        replaceWhat = replaceWhat.replace(/[-/^$*+?.()|[]{}]/g, '$&');
        var re = new RegExp(replaceWhat, 'g');
        return str.replace(re,replaceTo);
    }
    

    See Is there a RegExp.escape function in Javascript?


    Replace has an alternate form that takes 3 parameters and accepts a string:

    function name(str,replaceWhat,replaceTo){
        str.replace(replaceWhat,replaceTo,"g");
    }
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

    链接地址: http://www.djcxy.com/p/76822.html

    上一篇: 正则表达式或jQuery替换另一个字符串中的所有字符串匹配

    下一篇: JS使用变量替换所有出现的字符串