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:45

Using RegExp in JavaScript could do the job for you, just simply do something like below:

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

If you think of reuse, create a function to do that for you, but it's not recommended as it's only one line function, but again if you heavily get use of this, you can write something like this:

String.prototype.replaceAll = String.prototype.replaceAll || function(string, replaced) {
  return this.replace(new RegExp(string, 'g'), replaced);
};

and simply use it in your code over and over like below:

var str ="Test abc test test abc test test test abc test test abc";
str = str.replaceAll('abc', '');

But as I mention earlier, it won't make a huge difference in terms of lines to be written or performance, only caching the function may effect some faster performance on long strings and also a good practice of DRY code if you want to reuse.

查看更多
不再属于我。
3楼-- · 2018-12-31 18:46

//loop it until number occurrences comes to 0. OR simply copy/paste

    function replaceAll(find, replace, str) 
    {
      while( str.indexOf(find) > -1)
      {
        str = str.replace(find, replace);
      }
      return str;
    }
查看更多
谁念西风独自凉
4楼-- · 2018-12-31 18:46

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

查看更多
明月照影归
5楼-- · 2018-12-31 18:48

You can simply use below method

/**
 * Replace all the occerencess of $find by $replace in $originalString
 * @param  {originalString} input - Raw string.
 * @param  {find} input - Target key word or regex that need to be replaced.
 * @param  {replace} input - Replacement key word
 * @return {String}       Output string
 */
function replaceAll(originalString, find, replace) {
  return originalString.replace(new RegExp(find, 'g'), replace);
};
查看更多
明月照影归
6楼-- · 2018-12-31 18:49

Match against a global regular expression:

anotherString = someString.replace(/cat/g, 'dog');
查看更多
无与为乐者.
7楼-- · 2018-12-31 18:49

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.

查看更多
登录 后发表回答