如何在Javascript中使用replaceAll? [重复]

问题描述

|                                                                                                                   这个问题已经在这里有了答案:                                                      

解决方法

您需要进行全局替换。不幸的是,您不能使用字符串参数来执行此跨浏览器:您需要使用正则表达式:
ss.replace(/,/g,\'\\n\\t\');
g
修饰符使搜索成为全局。     ,您需要在此处使用regexp。请尝试以下
ss.replace(/,”\\n\\t”)
“ 1”表示要在全球范围内更换。     ,这是replaceAll的另一个实现。希望它可以帮助某人。
    String.prototype.replaceAll = function (stringToFind,stringToReplace) {
        if (stringToFind === stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind,stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };
然后,您可以使用它:
var myText = \"My Name is George\";                                            
var newText = myText.replaceAll(\"George\",\"Michael\");