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?
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?
For the sake of completeness, I got to thinking about which method I should use to do this. There are basically two ways to do this as suggested by the other answers on this page.
Note: In general, extending the built-in prototypes in JavaScript is generally not recommended. I am providing as extensions on the String prototype simply for purposes of illustration, showing different implementations of a hypothetical standard method on the String
built-in prototype.
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
};
Not knowing too much about how regular expressions work behind the scenes in terms of efficiency, I tended to lean toward the split and join implementation in the past without thinking about performance. When I did wonder which was more efficient, and by what margin, I used it as an excuse to find out.
On my Chrome Windows 8 machine, the regular expression based implementation is the fastest, with the split and join implementation being 53% slower. Meaning the regular expressions are twice as fast for the lorem ipsum input I used.
Check out this benchmark running these two implementations against each other.
As noted in the comment below by @ThomasLeduc and others, there could be an issue with the regular expression-based implementation if search
contains certain characters which are reserved as special characters in regular expressions. The implementation assumes that the caller will escape the string beforehand or will only pass strings that are without the characters in the table in Regular Expressions (MDN).
MDN also provides an implementation to escape our strings. It would be nice if this was also standardized as RegExp.escape(str)
, but alas, it does not exist:
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
We could call escapeRegExp
within our String.prototype.replaceAll
implementation, however, I'm not sure how much this will affect the performance (potentially even for strings for which the escape is not needed, like all alphanumeric strings).
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(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
Note: Regular expressions contain special (meta) characters, and as such it is dangerous to blindly pass an argument in the find
function above without pre-processing it to escape those characters. This is covered in the Mozilla Developer Network's JavaScript Guide on Regular Expressions, where they present the following utility function:
function escapeRegExp(str) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
So in order to make the replaceAll()
function above safer, it could be modified to the following if you also include escapeRegExp
:
function replaceAll(str, find, replace) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
function replaceAll(find, replace,str) { var re = new RegExp(find, 'g'); str = str.replace(re, replace); return str; }
– Click Upvote
Jul 17 '09 at 21:11
replaceAll
implementation is that it won't work if find
contains metacharacters.
– Martin Ender
Aug 27 '13 at 0:39
Note: Don't use this in real code.
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
str.split(search).join(replacement)
This used to be faster in some cases than using replaceAll
and a regular expression, but that doesn't seem to be the case anymore in modern browsers. So, this should really only be used as a quick hack to avoid needing to escape the regular expression, not in real code.
String.prototype.replaceAll = function(f,r){return this.split(f).join(r);}
. Usage: "My string".replaceAll('st', '');
produces "My ring"
– MacroMan
Sep 26 '14 at 11:50
replaceAll
function, and it becomes just as readable as anything else. Since performance is not bad, there's no reason to avoid this solution.
– youen
Apr 19 '18 at 8: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"
var sourceText
count the number of instances (numOfInstances
) using substring
or split and count the length (among other strategies) of thatWhichYouWantToReplace
then do for (var i = 0; i < numOfInstances; i++){ sourceText = sourceText.replace('thatWhichYouWantToReplace', '');
} or even easier just use a while loop (while sourceText.indexOf(thatWhichYouWantToReplace > -1){ sourceText = sourceText.replace(...)
) but I don't see why you would want to do it that way when using /g
is so easy and probably more performant.
– Zargold
Mar 20 '16 at 22:20
Here's a string prototype function based on the accepted answer:
String.prototype.replaceAll = function (find, replace) {
var str = this;
return str.replace(new RegExp(find, 'g'), replace);
};
EDIT
If your find
will contain special characters then you need to escape them:
String.prototype.replaceAll = function (find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};
Fiddle: http://jsfiddle.net/cdbzL/
find
contains characters like .
or $
that have special meanings in regex?
– callum
Oct 7 '13 at 11:30
var str = this
creates a second reference to the immutable string, to which the replace
method is applied, which in turn returns a new immutable string. these prototype functions return a new immutable string, if not, you'd be able to write someStrVar.replaceAll('o', '0');
and someStrVar
would be changed. Instead, you have to write someStrVar = someStrVar.replaceAll('o', '0');
<-- reassign to set the var to hold the new immutable string. there's no way around that. Try in console: x = 'foobar'; x.replaceAll('o', '0'); x;
– Elias Van Ootegem
Jun 15 '16 at 16:26
Update:
It's somewhat late for an update, but since I just stumbled on this question, and noticed that my previous answer is not one I'm happy with. Since the question involved replaceing a single word, it's incredible nobody thought of using word boundaries (\b
)
'a cat is not a caterpillar'.replace(/\bcat\b/gi,'dog');
//"a dog is not a caterpillar"
This is a simple regex that avoids replacing parts of words in most cases. However, a dash -
is still considered a word boundary. So conditionals can be used in this case to avoid replacing strings like cool-cat
:
'a cat is not a cool-cat'.replace(/\bcat\b/gi,'dog');//wrong
//"a dog is not a cool-dog" -- nips
'a cat is not a cool-cat'.replace(/(?:\b([^-]))cat(?:\b([^-]))/gi,'$1dog$2');
//"a dog is not a cool-cat"
basically, this question is the same as the question here: Javascript replace " ' " with " '' "
@Mike, check the answer I gave there... regexp isn't the only way to replace multiple occurrences of a subsrting, far from it. Think flexible, think split!
var newText = "the cat looks like a cat".split('cat').join('dog');
Alternatively, to prevent replacing word parts -which the approved answer will do, too! You can get around this issue using regular expressions that are, I admit, somewhat more complex and as an upshot of that, a tad slower, too:
var regText = "the cat looks like a cat".replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
The output is the same as the accepted answer, however, using the /cat/g expression on this string:
var oops = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/cat/g,'dog');
//returns "the dog looks like a dog, not a dogerpillar or cooldog" ??
Oops indeed, this probably isn't what you want. What is, then? IMHO, a regex that only replaces 'cat' conditionally. (ie not part of a word), like so:
var caterpillar = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
//return "the dog looks like a dog, not a caterpillar or coolcat"
My guess is, this meets your needs. It's not fullproof, of course, but it should be enough to get you started. I'd recommend reading some more on these pages. This'll prove useful in perfecting this expression to meet your specific needs.
http://www.javascriptkit.com/jsref/regexp.shtml
http://www.regular-expressions.info
Final addition:
Given that this question still gets a lot of views, I thought I might add an example of .replace
used with a callback function. In this case, it dramatically simplifies the expression and provides even more flexibility, like replacing with correct capitalisation or replacing both cat
and cats
in one go:
'Two cats are not 1 Cat! They\'re just cool-cats, you caterpillar'
.replace(/(^|.\b)(cat)(s?\b.|$)/gi,function(all,char1,cat,char2)
{
//check 1st, capitalize if required
var replacement = (cat.charAt(0) === 'C' ? 'D' : 'd') + 'og';
if (char1 === ' ' && char2 === 's')
{//replace plurals, too
cat = replacement + 's';
}
else
{//do not replace if dashes are matched
cat = char1 === '-' || char2 === '-' ? cat : replacement;
}
return char1 + cat + char2;//return replacement string
});
//returns:
//Two dogs are not 1 Dog! They're just cool-cats, you caterpillar
Match against a global regular expression:
anotherString = someString.replace(/cat/g, 'dog');
For replacing a single time use:
var res = str.replace('abc', "");
For replacing multiple times use:
var res = str.replace(/abc/g, "");
replace(/\n/g, '<br/>')
– Phan Van Linh
Sep 30 at 3:55
These are the most common and readable methods.
var str = "Test abc test test abc test test test abc test test abc"
Method-01:
str = str.replace(/abc/g, "replaced text");
Method-02:
str = str.split("abc").join("replaced text");
Method-03:
str = str.replace(new RegExp("abc", "g"), "replaced text");
Method-04:
while(str.includes("abc")){
str = str.replace("abc", "replaced text");
}
Output:
console.log(str);
// Test replaced text test test replaced text test test test replaced text test test replaced text
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'
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.
Using RegExp
in JavaScript could do the job for you, just simply do something like below code, don't forget the /g
after which standout for global:
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 use 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.
Replacing single quotes:
function JavaScriptEncode(text){
text = text.replace(/'/g,''')
// More encode here if required
return text;
}
This is the fastest version that doesn't use regular expressions.
replaceAll = function(string, omit, place, prevstring) {
if (prevstring && string === prevstring)
return string;
prevstring = string.replace(omit, place);
return replaceAll(prevstring, omit, place, string)
}
It is almost twice as fast as the split and join method.
As pointed out in a comment here, this will not work if your omit
variable contains place
, as in: replaceAll("string", "s", "ss")
, because it will always be able to replace another occurrence of the word.
There is another jsperf with variants on my recursive replace that go even faster (http://jsperf.com/replace-all-vs-split-join/12)!
if(place.replace(omit) === omit) {
No match, so it's safe to use replace loop } else {
Match so use different method like split and join }
– Cole Lawrence
Jul 10 '14 at 12:41
//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;
}
.indexOf
in a variable, and use this variable as the second parameter of .indexOf
(minus length of keyword, plus length of replacement string).
– Rob W
Oct 29 '13 at 11:33
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.
If what you want to find is already in a string, and you don't have a regex escaper handy, you can use join/split:
function replaceMulti(haystack, needle, replacement)
{
return haystack.split(needle).join(replacement);
}
someString = 'the cat looks like a cat';
console.log(replaceMulti(someString, 'cat', '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;
}
I like this method (it looks a little cleaner):
text = text.replace(new RegExp("cat","g"), "dog");
var str = "ff ff f f a de def";
str = str.replace(/f/g,'');
alert(str);
If the string contain similar pattern like abccc
, you can use this:
str.replace(/abc(\s|$)/g, "")
The simplest way to this without using any regex is split and join like code here :
var str="Test abc test test abc test test test abc test test abc";
str.split('abc').join('')
The previous answers are way too complicated. Just use the replace function like this:
str.replace(/your_regex_pattern/g, replacement_string);
Example:
var str = "Test abc test test abc test test test abc test test abc";
var res = str.replace(/[abc]+/g, "");
console.log(res);
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.]
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.
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);
};
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
I use p to store the result from the previous recursion replacement:
function replaceAll(s, m, r, p) {
return s === p || r.contains(m) ? s : replaceAll(s.replace(m, r), m, r, s);
}
It will replace all occurrences in the string s until it is possible:
replaceAll('abbbbb', 'ab', 'a') → 'abbbb' → 'abbb' → 'abb' → 'ab' → 'a'
To avoid infinite loop I check if the replacement r contains a match m:
replaceAll('abbbbb', 'a', 'ab') → 'abbbbb'
aba
inababa
withca
, which result do you expect?caba
?abca
?cca
? – reinierpost Aug 2 at 12:58