Javascript Replace All method

While working on my latest project requirement I found a strange issue in basic Javascript. replace method is not replacing all occurrence of the search key, it just replacing the first occurrence.

Synatx
string.replace(regexp/substr,newstring)
But

   var teststring = 'test test string';
    teststring .replace('test','test2');

will give you only ‘test2 test string’ not the expected one ‘test2 test2 string‘.

In order to get expected result we must  userregular expressions as below

var teststring = 'test test string';
teststring .replace(/test/g,'test2');

which will give u ‘test2 test2 string

Note: In Many sites, people are added many misleading information  like basic Javascript is not capable for this and it can achieve only through some specific frameworks only or only through custom functions.  So please understand the real power basic javscript.

 

Subin George
  • Kip Wurster

    Couldn’t have said it better myself.