How do I do global string replace without needing to escape everything?

前端 未结 4 603
不思量自难忘°
不思量自难忘° 2021-01-23 21:02

I want to replace all occurences of a pattern in a string by another string. For example, lets convert all \"$\" to \"!\":

\"$$$\" -> \"!!!\"
<
相关标签:
4条回答
  • 2021-01-23 21:16

    You can give the regest as a string and provide a third argument for the flags you want

    https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

    "$$$".replace("$", "!", "g");
    
    0 讨论(0)
  • 2021-01-23 21:19

    "Plain string.replace replaces only the first match"

    In that case, depending on how efficient you need the replace operation to be, you could do:

    String.prototype.my_replace_all_simple = function(f, r) {
        var newstr = "";
        for (var i = 0; i < this.length; ++i) {
            if (this[i] == f) {
                newstr += r;
            } else {
                newstr += this[i];
            }
        }
        return newstr;
    };
    

    or

    String.prototype.my_replace_all = function (f, r) {
        if (this.length === 0 || f.length === 0) {
            return this;
        }
        var substart = 0;
        var end = this.length;
        var newstr = "";
        while (true) {
            var subend = this.indexOf(f, substart);
            if (subend === -1) subend = end;
            newstr += this.substring(substart, subend);
            if (subend === end) {
                break;
            }
            newstr += r;
            substart = subend + f.length;
        }
        return newstr;
    };
    // Adapted from C++ code that uses iterators.
    // Might have converted it incorrectly though.
    

    for example.

    But, I'd just use Mark's suggested way.

    0 讨论(0)
  • 2021-01-23 21:33

    try this:

    function replaceAll(txt, replace, with_this) {
      return txt.replace(new RegExp(replace, 'g'),with_this);
    }
    
    0 讨论(0)
  • 2021-01-23 21:34

    There is no standard regexp escape function in Javascript.

    You can write your own (source) or get it from your library (dojo example)

    function escape(s) {
        return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
    };
    

    This allows us to create the custom regex object at runtime

    function replace_all(string, pattern, replacement){
        return string.replace( new RegExp(escape(pattern), "g"), replacement);
    }
    
    0 讨论(0)
提交回复
热议问题