All posts tagged javscript replaceall

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

Continue reading →