How to replace all occurrences of a string in Java

2018-12-31 18:13发布

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楼-- · 2018-12-31 18:42
var str = "ff ff f f a de def";
str = str.replace(/f/g,'');
alert(str);

http://jsfiddle.net/ANHR9/

查看更多
几人难应
3楼-- · 2018-12-31 18:43

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

查看更多
公子世无双
4楼-- · 2018-12-31 18:43
str = str.replace(new RegExp("abc", 'g'), "");

worked better for me than the above answers. so new RegExp("abc", 'g') creates a RegExp what matches all occurence ('g' flag) of the text ("abc"). The second part is what gets replaced to, in your case empty string (""). str is the string, and we have to override it, as replace(...) just returns result, but not overrides. In some cases you might want to use that.

查看更多
与风俱净
5楼-- · 2018-12-31 18:43
var string  = 'Test abc Test abc Test abc Test abc'
string = string.replace(/abc/g, '')
console.log(string)
查看更多
何处买醉
6楼-- · 2018-12-31 18:43

Although people have mentioned the use of regex but there's a better approach if you want to replace the text irrespective of the case of the text. Like uppercase or lowercase. Use below syntax

//Consider below example
originalString.replace(/stringToBeReplaced/gi, '');

//Output will be all the occurrences removed irrespective of casing.

You can refer the detailed example here.

查看更多
长期被迫恋爱
7楼-- · 2018-12-31 18:44
str = str.replace(/abc/g, '');

Or try the replaceAll function from here:

What are useful JavaScript methods that extends built-in objects?

str = str.replaceAll('abc', ''); OR

var search = 'abc';
str = str.replaceAll(search, '');

EDIT: Clarification about replaceAll availability

The 'replaceAll' method is added to String's prototype. This means it will be available for all string objects/literals.

E.g.

var output = "test this".replaceAll('this', 'that');  //output is 'test that'.
output = output.replaceAll('that', 'this'); //output is 'test this'
查看更多
登录 后发表回答