Skip to content

Misconceptions on URL encoding and replace() in JavaScript

JavaScript methods that seems to do what they’re supposed to do, but not always.

Escape

Take for example the method of URL encoding a piece of string. There’s a pretty good chance that you run into a page that advises to use the escape() method for that. And although it seems to work, it will only handle ASCII-characters. You should use the newer method encodeURIComponent() for that.

The reason why escape() is still popular is probably because that method has been around longer, seems to do what you think it should do and is easier to remember. But if you use it for URL encoding, the end result will be buggy. Just Google for ‘escape JavaScript URL’ and you’ll find lots of misinformation on this subject. xkr.us has a a good web page on that subject.

Replace

Another one: replace(). That too seems to do what you think it should. Right? Well, not really. Only the first occurrence of a given string is replaced with another. Once again this is a method that pops up when you search for something like that and quickly copy-paste into your code. If you want to replace all strings you’ll have to use regular expressions. Instead of replace('foo', 'bar') you’ll have to write replace(/foo/g, 'bar'). Please pay attention to the lowercase ‘g’ after the regular expression. That’s what toggles the Global replace.

Bookmark and Share

Leave a response