我有这个字符串:
"Test abc test test abc test test test abc test test abc"
正在做:
str = str.replace('abc', '');
似乎只删除了abc
上面字符串中的第一个匹配项。
如何替换所有出现的内容?
如何替换所有出现的字符串?
我有这个字符串:
"Test abc test test abc test test test abc test test abc"
正在做:
str = str.replace('abc', '');
似乎只删除了abc
上面字符串中的第一个匹配项。
如何替换所有出现的内容?
第147篇《如何替换所有出现的字符串?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点
If the string contain similar pattern like abccc
, you can use this:
str.replace(/abc(\s|$)/g, "")
var str = "ff ff f f a de def";
str = str.replace(/f/g,'');
alert(str);
我喜欢这种方法(看起来更干净):
text = text.replace(new RegExp("cat","g"), "dog");
function replaceAll(str, find, replace) {
var i = str.indexOf(find);
if (i > -1){
str = str.replace(find, replace);
i = i + replace.length;
var st2 = str.substring(i);
if(st2.indexOf(find) > -1){
str = str.substring(0,i) + replaceAll(st2, find, replace);
}
}
return str;
}
//循环播放,直到出现的次数变为0。或者简单地复制/粘贴
function replaceAll(find, replace, str)
{
while( str.indexOf(find) > -1)
{
str = str.replace(find, replace);
}
return str;
}
这是不使用正则表达式的最快版本。
replaceAll = function(string, omit, place, prevstring) {
if (prevstring && string === prevstring)
return string;
prevstring = string.replace(omit, place);
return replaceAll(prevstring, omit, place, string)
}
它的速度几乎是split and join方法的两倍。
如此处的注释中所指出的,如果您的omit
变量包含place
,如:中的,这将不起作用replaceAll("string", "s", "ss")
,因为它始终可以替换该单词的另一个出现。
我的递归替换中还有另一个jsperf,它的变体运行得更快(http://jsperf.com/replace-all-vs-split-join/12)!
使用正则表达式:
str.replace(/abc/g, '');
这些是最常见且易读的方法。
var str = "Test abc test test abc test test test abc test test abc"
方法1:
str = str.replace(/abc/g, "replaced text");
方法2:
str = str.split("abc").join("replaced text");
方法3:
str = str.replace(new RegExp("abc", "g"), "replaced text");
方法4:
while(str.includes("abc")){
str = str.replace("abc", "replaced text");
}
输出:
console.log(str);
// Test replaced text test test replaced text test test test replaced text test test replaced text
相似问题
问题类别
The previous answers are way too complicated. Just use the replace function like this:
Example: