Be careful when replacing strings in JavaScript

November 4th, 2013

Sometimes, methods that you think you know well might surprise you and bring you headaches if you don't read the documentation carefully. One of these methods is the JavaScript String.replace method. Let's start with the obvious scenario:


'abc'.replace('bc', 'x')        // ax
Quite simple right? You expect the bc substring to be replaced with x string and this is exactly what you get. But what if you don't control the string you're replacing with? This string might come from a user input or be a content of a file read from a file system:

'abc'.replace('bc', userinput)
The result of this might surprise you depending on what the userinput string contains.

var userinput = 'x';
'abc'.replace('bc', userinput)  // ax
Still ok. But what about now:

var userinput = 'x$&';
'abc'.replace('bc', userinput)  // axbc
What? Yes, this is because the second parameter, the replacement string, can contain special replacement patterns. E.g. the replacement pattern $& means Insert the matched substring. A safe way of replacing strings with new substrings that you don't control is:

var userinput = 'x$&';
'abc'.replace('bc', function(match) { return userinput; })  // ax$&

This might surprise you when you're coming from e.g. Python world, where this does not apply.

Discussion



comments powered by Disqus