如何使用replaceAll Javascript () .............

How to use replaceAll() in Javascript.........................?

本文关键字:Javascript replaceAll 何使用      更新时间:2023-09-26

我使用下面的代码来替换,用'n't

ss.replace(',',''n't')

,我想用'n替换字符串中的所有逗号,所以添加这个ss.replaceAll(',',''n't')它不起作用..........!

你知道怎么越过........吗?

谢谢。

您需要进行全局替换。不幸的是,您不能使用字符串参数跨浏览器执行此操作:您需要使用regex:

ss.replace(/,/g, ''n't');

g修饰符使搜索全局

这里需要使用regexp。请尝试以下

ss.replace(/,/g,”'n't”)

g表示全局替换

这是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");