javascript的replaceAll函数

网上很多文章写这个问题的,但是都是使用正则,遇上有转义符的时候用起来也不是很方便。 使用正规的版本如下 :

String.prototype.replaceAll = function (exp, newStr) {
    return this.replace(new RegExp(exp, "gm"), newStr);
};

 今天又遇上这个函数搞不定的情况。决定折腾一下。

用deepseek生成的函数。

 

 

 

String.prototype.replaceAll = function (search, replacement) {
    var str = this;
    if (typeof search !== 'string' || search.length === 0) {
        return str;
    }

    let result = '';
    let lastIndex = 0;
    let currentIndex = str.indexOf(search);

    while (currentIndex !== -1) {
        result += str.substring(lastIndex, currentIndex) + replacement;
        lastIndex = currentIndex + search.length;
        currentIndex = str.indexOf(search, lastIndex);
    }

    return result + str.substring(lastIndex);
};

 发现结果还不错。符合要求。

posted on 2025-07-16 15:41  kalamansi  阅读(6)  评论(0)    收藏  举报

导航