Treehouse

Replace All Occurrences of a String in JavaScript

By on  

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!

ydkjs-3.png

Recent Features

  • Convert XML to JSON with JavaScript

    If you follow me on Twitter, you know that I've been working on a super top secret mobile application using Appcelerator Titanium.  The experience has been great:  using JavaScript to create easy to write, easy to test, native mobile apps has been fun.  My...

  • Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

Incredible Demos

Discussion

  1. Richard

    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.

  2. Jay

    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_replace in PHP, but it is very similar to preg_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!

  3. “.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.

  4. David, just a question, whats the name of comments system that you had? WDC or something like that. Thx

  5. elron

    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!

  6. Yang

    Could you tell me what is code to create the copy to clipboard button, please?

  7. also have this problem. thanks for your perfect method.
    I use replace(/\+/g, ‘ ‘) replace “+” to space

  8. gadget

    Here is another article about javascript replace you people might be interested @

    http://gadgets-code.com/javascript-replace-method-review

    :)

  9. jonathan

    thanks fir that simple but super usefull tip

  10. Abhishek

    use ‘gi’ in place of ‘g’ to replace the string irrespective case, i.e to replace for insenstive case.

  11. quote -replace(/\+/g, ‘ ‘) replace “+” to space”-unquote worked like a charm! for decodeURIComponent after banging my head for two hours!

    //on serverside
    server.encode(uri) 
    //on client side
    var str = decodeURIComponent(uri);
    str.Replace(/\+/g,' ');
    
  12. Pragya Shukla

    Thanks David. It helps me a lot.

  13. 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.

  14. Pathiv

    Thanks mate….it worked for me….

  15. Thanks David. Works for me!

  16. Leandrom

    thank you!

  17. […] doesn’t replace all occurrences of the search, just the first.  But, you can use a regular expression and the global flag (/g) need to be […]

  18. […] doesn’t replace all occurrences of the search, just the first.  But, you can use a regular expression and the global flag (/g) need to be […]

  19. […] JavaScript 初学者意外的是,字符串的 replace 方法并不会 替换所有匹配的子串——而仅仅替换第一次匹配。当然 JavaScript […]

  20. […] surprise to many JavaScript newbies is that String’s replace method doesn’t replace all occurrences of the needle– just the first occurrence. Of course seasoned JavaScript vets know that a regular expression […]

  21. […] JavaScript 初学者意外的是,字符串的 replace 方法并不会 替换所有匹配的子串——而仅仅替换第一次匹配。当然 JavaScript […]

  22. […] JavaScript 初学者意外的是,字符串的 replace 方法并不会 替换所有匹配的子串——而仅仅替换第一次匹配。当然 JavaScript […]

  23. […] JavaScript 初学者意外的是,字符串的 replace 方法并不会 替换所有匹配的子串——而仅仅替换第一次匹配。当然 JavaScript […]

  24. […] JavaScript 初学者意外的是,字符串的 replace 方法并不会 替换所有匹配的子串——而仅仅替换第一次匹配。当然 JavaScript […]

  25. […] JavaScript 初学者意外的是,字符串的 replace 方法并不会 替换所有匹配的子串——而仅仅替换第一次匹配。当然 JavaScript […]

  26. […] 和 /i标志位 令很多 JavaScript 初学者意外的是,字符串的 replace 方法并不会 替换所有匹配的子串——而仅仅替换第一次匹配。当然 JavaScript […]

  27. […] JavaScript 初学者意外的是,字符串的 replace 方法并不会 替换所有匹配的子串——而仅仅替换第一次匹配。当然 JavaScript […]

  28. […] JavaScript 初学者意外的是,字符串的 `replace` 方法并不会  替换所有匹配的子串 ——而仅仅替换第一次匹配。当然 JavaScript […]

  29. […] JavaScript 初学者意外的是,字符串的 replace 方法并不会 替换所有匹配的子串——而仅仅替换第一次匹配。当然 JavaScript […]

  30. Bhushan

    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 ?

  31. […] JavaScript 初学者意外的是,字符串的 replace 方法并不会 替换所有匹配的子串——而仅仅替换第一次匹配。当然 JavaScript […]

  32. […] JavaScript 初学者意外的是,字符串的 replace 方法并不会 替换所有匹配的子串——而仅仅替换第一次匹配。当然 JavaScript […]

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!