Wednesday 4 January 2017

JavaScript replace() method's deviousness!

There is a trick to this method, if you do:
var test = 'old old old';
test = test.replace('old','new');
console.log(test);

The output would not be as expected, you would get:

'new old old'

However, if you remove the quotes and add regex tags:

test = test.replace(/old/g,'new');

You will get every instance replaced in your string.


My pleasure!

No comments:

Post a Comment

Devlog 8: AI and Radar explanation.