Using encodeURI() vs. escape() for utf-8 strings in JavaScript

SeanPlusPlus picture SeanPlusPlus · Jul 28, 2014 · Viewed 78.7k times · Source

I am handling utf-8 strings in JavaScript and need to escape them.

Both escape() / unescape() and encodeURI() / decodeURI() work in my browser.

escape()

> var hello = "안녕하세요"
> var hello_escaped = escape(hello)
> hello_escaped
  "%uC548%uB155%uD558%uC138%uC694"
> var hello_unescaped = unescape(hello_escaped)
> hello_unescaped
  "안녕하세요"

encodeURI()

> var hello = "안녕하세요"    
> var hello_encoded = encodeURI(hello)
> hello_encoded
  "%EC%95%88%EB%85%95%ED%95%98%EC%84%B8%EC%9A%94"
> var hello_decoded = decodeURI(hello_encoded)
> hello_decoded
  "안녕하세요"

However, Mozilla says that escape() is deprecated.

Although encodeURI() and decodeURI() work with the above utf-8 string, the docs (as well as the function names themselves) tell me that these methods are for URIs; I do not see utf-8 strings mentioned anywhere.

Simply put, is it okay to use encodeURI() and decodeURI() for utf-8 strings?

Answer

Sumukh Barve picture Sumukh Barve · Nov 15, 2015

Hi!

When it comes to escape and unescape, I live by two rules:

  1. Avoid them when you easily can.
  2. Otherwise, use them.

Avoiding them when you easily can:

As mentioned in the question, both escape and unescape have been deprecated. In general, one should avoid using deprecated functions.

So, if encodeURIComponent or encodeURI does the trick for you, you should use that instead of escape.

Using them when you can't easily avoid them:

Browsers will, as far as possible, strive to achieve backwards compatibility. All major browsers have already implemented escape and unescape; why would they un-implement them?

Browsers would have to redefine escapeand unescape if the new specification requires them to do so. But wait! The people who write specifications are quite smart. They too, are interested in not breaking backwards compatibility!

I realize that the above argument is weak. But trust me, ... when it comes to browsers, deprecated stuff works. This even includes deprecated HTML tags like <xmp> and <center>.

Using escape and unescape:

So naturally, the next question is, when would one use escape or unescape?

Recently, while working on CloudBrave, I had to deal with utf8, latin1 and inter-conversions.

After reading a bunch of blog posts, I realized how simple this was:

var utf8_to_latin1 = function (s) {
    return unescape(encodeURIComponent(s));
};
var latin1_to_utf8 = function (s) {
    return decodeURIComponent(escape(s));
};

These inter-conversions, without using escape and unescape are rather involved. By not avoiding escape and unescape, life becomes simpler.

Hope this helps.