如何在Javascript中使用replaceAll().........................?

时间:2011-04-13 12:43:30

标签: javascript

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

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

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

任何想法如何克服........?

谢谢。

3 个答案:

答案 0 :(得分:14)

您需要进行全局替换。不幸的是,你不能用字符串参数进行跨浏览:你需要一个正则表达式:

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

g修饰符使搜索成为全局。

答案 1 :(得分:2)

你需要在这里使用正则表达式。请尝试以下

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

g表示全局替换它。

答案 2 :(得分: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");