Getting Started with Adobe After Effects - Part 6: Motion Blur
A collection of quick technology learning tips from what people around you learn every day

JavaScript - Replace function surprise problem of replacing only one occurrence and workaround for this

Jul 21 2011 4:35AM by Ramireddy   

Today I got a surprising problem of JavaScript replace() method is replacing only the first occurrence. Suppose we have a string "AABAA", If we wants to replace "AA" with "A", then the replace("AABAA","AA","A") returning "ABAA" only. It is replacing only the first occurrence. You can see below script returns "ABAA".

           var tmp = "AABAA";
           tmp = tmp.replace("AA","A");
           alert(tmp);  

A quick search in Google indicates that by changing "AA" with "/AA/g" will replace all occurrences. By specifying option "g" we are performing global search. You can see below script will return output ABA. Remember while specifying this option, you need to make it as regular expression. "/" character indicates start and end of regular expression.

           var tmp = "AABAA";
           tmp = tmp.replace(/AA/g,"A");
           alert(tmp);   
Read More..   [8 clicks]

Published under: Internet and Web Tips ·  ·  ·  · 


Ramireddy
2 · 41% · 12972
8
 
3
 
 
0
Incorrect
 
0
Interesting
 
0
Forgotten



Submit

2  Comments  

  • you can also use the following code in javascript if you are not sure for the second instance would replace or not.

    var tmp = "AABAA";
    var sNewStr = '';
    var newStringArray = new Array();
    newStringArray = tmp.split('AA');
    sNewStr = newStringArray .join('A');
    
    commented on Jul 21 2011 10:39PM
    Paresh Bhavsar
    1911 · 0% · 9
  • Wow.....This is an excellent technique..

    commented on Jul 22 2011 1:20AM
    Ramireddy
    2 · 41% · 12972

Your Comment


Sign Up or Login to post a comment.

"JavaScript - Replace function surprise problem of replacing only one occurrence and workaround for this" rated 5 out of 5 by 8 readers
JavaScript - Replace function surprise problem of replacing only one occurrence and workaround for this , 5.0 out of 5 based on 8 ratings
    Copyright © Rivera Informatic Private Ltd Contact us      Privacy Policy      Terms of use      Report Abuse      Advertising      [ZULU1097]