如何在 Javascript 中使用 replaceAll() .....................................
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5649403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use replaceAll() in Javascript.........................?
提问by Warrior
I am using below code to replace , with \n\t
我正在使用下面的代码替换 , 与 \n\t
ss.replace(',','\n\t')
and i want to replace all the coma in string with \n so add this ss.replaceAll(',','\n\t')
it din't work..........!
我想用 \n 替换字符串中的所有昏迷,所以添加ss.replaceAll(',','\n\t')
它它不起作用.........!
any idea how to get over........?
知道如何克服......?
thank you.
谢谢。
回答by lonesomeday
You need to do a global replace. Unfortunately, you can't do this cross-browser with a string argument: you need a regex instead:
您需要进行全局替换。不幸的是,您不能使用字符串参数执行此跨浏览器:您需要一个正则表达式:
ss.replace(/,/g, '\n\t');
The g
modifer makes the search global.
该g
修改器使得搜索全球。
回答by Eldar Djafarov
You need to use regexp here. Please try following
您需要在此处使用正则表达式。请尝试以下
ss.replace(/,/g,”\n\t”)
g
means replace it globally.
g
意味着全局替换它。
回答by scripto
Here's another implementation of replaceAll. Hope it helps someone.
这是 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;
};
Then you can use it:
然后你可以使用它:
var myText = "My Name is George";
var newText = myText.replaceAll("George", "Michael");