Say I have this string:
Test abc test test abc test test
test abc test test abc
Doing
str=str.replace('abc','');
Seems only to remove the first occurrence of abc
in the string above. How can I replace ALL occurrences of it?
Say I have this string:
Test abc test test abc test test
test abc test test abc
Doing
str=str.replace('abc','');
Seems only to remove the first occurrence of abc
in the string above. How can I replace ALL occurrences of it?
str = str.replace(/abc/g, '');
In response to comment:
var find = 'abc';
var re = new RegExp(find, 'g');
str = str.replace(re, '');
In response to Click Upvote's comment, you could simplify it even more:
function replaceAll(find, replace, str) {
return str.replace(new RegExp(find, 'g'), replace);
}
str = str.replace(/abc/g, '');
Or try the replaceAll function from here:
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'
You could try using your existing code, then throw it in a while loop... Not sure what this will do for performance, but it will definitely get the job done!
var exists = false;
if (str.indexOf('abc') > 0)
exists = true; // does 'abc' exist in my string?
while (exists) // replace 'abc' as long as it exists
{
str = str.replace('abc', '');
if (str.indexOf('abc') > 0)
exists = true;
else
exists = false;
}
As an alternative to regular expressions for a simple literal string, you could use
str = "Test abc test test abc test...".split("abc").join("");
The general pattern is
string.split(search).join(replacement)
I would wrap it in a function so it's more obvious what's going on.