In javascript string replace doesn’t do what you think it does

When doing a string replace in javascript if you try something like this:

var str = 'test';
str.replace('t', 's');

You’ll find that the result is:


The replace method in javascript is not a global replace. Instead it does a single replace and moves on.

If you want to do a global replace try using a regular expression instead:

var str = 'test';
str.replace(/t/g, 's');

the result will be:


The reason for that is the ‘g’ hanging of the end of the expression /t/g. That tells javascript that the replace should be global.

Leave a Reply