Replace All Occurrences of a String in JavaScript
One thing you may have noticed is that JavaScript's String.replace() method doesn't act like replacement methods in other languages. Take the following for example:
var replaced = 'The MooTools JavaScript library is is great. I have never loved any code as I have MooTools!'.replace('MooTools','MooTools FTW!');
The above code will only replace the first occurrence of "MooTools" -- not every occurrence like PHP's str_replace() would. To replace every occurrence of a string in JavaScript, you must provide the replace() method a regular expression with a global modifier as the first parameter:
var replaced = 'The MooTools JavaScript library is is great. I have never loved any code as I have MooTools!'.replace(/MooTools/g,'MooTools FTW!');
Remember that you must escape special characters within your regular expression. And oh -- how convenient! MooTools provides a method that will do that for you!
![Camera and Video Control with HTML5]()
Client-side APIs on mobile and desktop devices are quickly providing the same APIs. Of course our mobile devices got access to some of these APIs first, but those APIs are slowly making their way to the desktop. One of those APIs is the getUserMedia API...
![Chris Coyier’s Favorite CodePen Demos]()
David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...
![Making the Firefox Logo from HTML]()
When each new t-shirt means staving off laundry for yet another day, swag quickly becomes the most coveted perk at any tech company. Mozilla WebDev had pretty much everything going for it: brilliant people, interesting problems, awesome office. Everything except a t-shirt.
That had to change.
The basic...
![Creating the Treehouse Frog Animation]()
Before we start, I want to say thank you to David for giving me this awesome opportunity to share this experience with you guys and say that I'm really flattered. I think that CSS animations are really great. When I first learned how CSS...
I had this issue before, didn’t knew the answer was so simple. Out of frusteration I actually used php.js because I couldn’t figure it out. Thnx man.
FTR, JS’s replace function DOES act like replace functions in other languages, just perhaps not the ones you’re expecting it to.
It doesn’t work like
str_replacein PHP, but it is very similar topreg_replace.As long as developers are aware that .replace is a regular expression replacement method, I think it’s pretty straightforward.
http://www.w3schools.com/jsref/jsref_replace.asp
It should also be noted that one can create a regular expression using something like:
var regex = new RegExp('MooTools', 'g');And that regular expression can be used in the replace function (first parameter). Which is helpful if you ever want to use the contents of a variable in your replacement:
http://tommcfarlin.com/2008/03/11/using-local-variables-with-javascripts-replace-function/
Don’t forget to escape!
“.replace is a regular expression replacement method” (@Jay)
I think that’s quite misleading. From what you’ve said one would assume that the replace-method’s first argument is converted to a regular expression implicitly when in fact, if you pass a string, it’s treated as literal text and is not converted to a RegExp object.
Also, just to clarify, /regex/ is the same as RegExp(‘regex’) – which, btw, doesn’t require the new operator.
David, just a question, whats the name of comments system that you had? WDC or something like that. Thx
can it replace the page itself?
i mean, insted of ““, it will write ““,
or insted if “<iframe>”, it will write “” (“<” is “<")
waiting for a response.
thanks!
Could you tell me what is code to create the copy to clipboard button, please?
also have this problem. thanks for your perfect method.
I use replace(/\+/g, ‘ ‘) replace “+” to space
Here is another article about javascript replace you people might be interested @
http://gadgets-code.com/javascript-replace-method-review
:)
thanks fir that simple but super usefull tip
use ‘gi’ in place of ‘g’ to replace the string irrespective case, i.e to replace for insenstive case.
quote -replace(/\+/g, ‘ ‘) replace “+” to space”-unquote worked like a charm! for decodeURIComponent after banging my head for two hours!
Thanks David. It helps me a lot.
newCats = ['lions', 'leopards', 'cats']; console.log( newCats.toString().replace(',',', ','g') );lions, leopards, cats /* and not lions,leopards,cats */
no need for // in the regex argument if it’s a simple expression.
Thanks mate….it worked for me….
Thanks David. Works for me!
thank you!
Hi
I need to replace the break in the string. I’m writing each character using plus so that you can unserstand.
”. Remove all the + from above string, and i need to replace that string within another string.
Can you please tell me how to do it ?
We can also pass the
iparameter in the regex to keep it case insensitive. Also we can create a function that would do the same and attach it to the String Obj using prototype, say something likeString.prototype.replaceAll…