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

前端 未结 4 736
不思量自难忘°
不思量自难忘° 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: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.

提交回复
热议问题