How to replace all occurrences of a string?

2020-01-22 11:01发布

I have this string:

"Test abc test test abc test test test abc test test abc"

Doing:

str = str.replace('abc', '');

seems to only remove the first occurrence of abc in the string above.

How can I replace all occurrences of it?

30条回答
趁早两清
2楼-- · 2020-01-22 11:08

Using a regular expression with the g flag set will replace all:

someString = 'the cat looks like a cat';
anotherString = someString.replace(/cat/g, 'dog');
// anotherString now contains "the dog looks like a dog"

See here also

查看更多
祖国的老花朵
3楼-- · 2020-01-22 11:11

If you are trying to ensure that the string you are looking for won't exist even after the replacement, you need to use a loop.

For example:

var str = 'test aabcbc';
str = str.replace(/abc/g, '');

When complete, you will still have 'test abc'!

The simplest loop to solve this would be:

var str = 'test aabcbc';
while (str != str.replace(/abc/g, '')){
   str.replace(/abc/g, '');
}

But that runs the replacement twice for each cycle. Perhaps (at risk of being voted down) that can be combined for a slightly more efficient but less readable form:

var str = 'test aabcbc';
while (str != (str = str.replace(/abc/g, ''))){}
// alert(str); alerts 'test '!

This can be particularly useful when looking for duplicate strings.
For example, if we have 'a,,,b' and we wish to remove all duplicate commas.
[In that case, one could do .replace(/,+/g,','), but at some point the regex gets complex and slow enough to loop instead.]

查看更多
聊天终结者
4楼-- · 2020-01-22 11:12

I like this method (it looks a little cleaner):

text = text.replace(new RegExp("cat","g"), "dog"); 
查看更多
何必那么认真
5楼-- · 2020-01-22 11:12

Just add /g

document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');

to

// Replace 'hello' string with /hello/g regular expression.
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');

/g means global

查看更多
仙女界的扛把子
6楼-- · 2020-01-22 11:13

For replacing a single time use:

var res = str.replace('abc', "");

For replacing multiple times use:

var res = str.replace(/abc/g, "");
查看更多
一夜七次
7楼-- · 2020-01-22 11:13

Say you want to replace all the 'abc' with 'x':

let some_str = 'abc def def lom abc abc def'.split('abc').join('x')
console.log(some_str) //x def def lom x x def

I was trying to think about something more simple than modifying the string prototype.

查看更多
登录 后发表回答