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:
Doing
seems to only remove the first occurrence of |
||||
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 Regular Expression Based Implementation
Split and Join (Functional) Implementation
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 Win8 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. EDITAs noted in the comment below by @ThomasLeduc and others, there could be an issue with the Regular Expression based implementation if MDN also provides an implementation to escape our strings, it would be nice if this was also standardized as
We could call I will play with this on jsperf and update this answer again with a new benchmark. |
|||||||||||||||||||||
|
In response to comment:
In response to Click Upvote's comment, you could simplify it even more:
Note: Regular expressions contain special (meta) characters, and as such it is dangerous to blindly pass an argument in the
So in order to make the
|
|||||||||||||||||||||
|
Note: Don't use this in real code. As an alternative to regular expressions for a simple literal string, you could use
The general pattern is
This used to be faster in some cases than using |
|||||||||||||||||||||
|
Using a regular expression with the
See here also |
|||||||||
|
Here's a string prototype function based on the accepted answer:
EDIT If your
Fiddle: http://jsfiddle.net/cdbzL/ |
|||||||||||||||||||||
|
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 (
This is a simple regex that avoids replacing parts of words in most cases. However, a dash
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!
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:
The output is the same as the accepted answer, however, using the /cat/g expression on this string:
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:
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
|
|||||||||||||
|
Match against a global regular expression:
|
|||
|
Or try the replaceAll function from here: What are useful JavaScript methods that extends built-in objects?
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.
|
|||||||||||||||||
|
This is the fastest version that doesn't use regex
it is almost twice as fast as split and join method. As pointed out in a comment here, this will not work if your There is another jsperf with variants on my recursive replace that go even faster!(http://jsperf.com/replace-all-vs-split-join/12) |
|||||||||||||||||
|
//loop it until number occurrences comes to 0. OR simply copy/paste
|
|||||||||
|
use a regex:
|
||||
|
|
||||
|
Not really much better than using a regexp, but multiple replacements can alternatively be achieved this way:
|
|||||||||||||
|
|
|||
|
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:
|
||||
|
|
|||||||||
|
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:
When complete, you will still have 'test abc'! The simplest loop to solve this would be:
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:
This can be particularly useful when looking for duplicate strings. |
|||||
|
I like this method, it looks a little cleaner.
|
|||||||||
|
Note: I can't comment yet, so I posted this as an answer, though there is some research information that could go in an answer. I also can't post more than 2 links, Split+join vs. regular expressionI tested out the Some research laterIE is way less used than I thought it is (statistics: gsN2NstatcounterN2NcomN0N#allN1NbrowserN1NwwN1NmonthlyN1N200812N1N201407), so the above still kinda applies, but only if you are very, very sure that IE is going to be the primarily used browser on that page. EDIT:I've made IE, Firefox and Chrome bots on jsperfN2NcomN0NreplaceN1NallN1NvsN1NsplitN1NjoinN0N13 (Before, there was data only about a version of Chrome). Look into the source code in the top of the page and copy the fastest function. Wow! I can't believe how fast i typed function. IE&Chrome - iterative replace() Firefox - split&join (way better than all others) End-note: English isn't my first language, so this took me some time to correct statements and English and the red-wavey underlining (indicating word not in mother language vocabulary) under most of the words was annoying too (I think there's an HTML attribute against that). I do realize the previous sentence is not grammatically correct. |
||||
|
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
You can refer the detailed example here. |
|||||
|
Well, quite late, but if someone reads this... maybe this is just what you needed... say you want to replace all the 'abc' with 'x':
Hope it helps... i was trying to think about something more simple than modifying the string prototype. Abrazo. |
|||||||||||||
|
Simple... Replacing single quotes:
|
|||||||||
|
My implementation, very self explanatory
|
|||||||||||||
|
Just add
to
|
||||
|
You can simply use below method
|
||||
|
Following function works for me:
now call the functions like this:
Simply copy and paste this code in your browser console to TEST. |
|||
|
This is very simplest way i think. |
|||||
|
for replace all kind of character try this code
so this method will solve this issue.
i was using ajax and i have need to send parameters in json format then my method is look like is
|
|||
|
If using a library is an option for you then you will get the benefits of the testing and community support that goes with a library function. For example, the string.js library has a replaceAll() function that does what you're looking for:
|
||||
|
Something little different by using recursion. I use p to store the result from the previous replacement:
It will replace all occurrences in the string s until it is possible:
To avoid infinite loop I check if the replacement r contains a match m:
|
|||
|
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
var str = 'abcabcbabc'; str.replace(/a/g, 'x'); --> 'xbcxbcxbc
– FedericoCapaldo Jul 6 '16 at 18:33