在JavaScript中使用encodeURI()与escape()for utf-8字符串

Sea*_*lus 18 javascript unicode encode escaping utf-8

我在JavaScript中处理utf-8字符串并需要转义它们.

escape()/ unescape()和encodeURI()/ decodeURI()都可以在我的浏览器中使用.

逃逸()

> var hello = "?????"
> var hello_escaped = escape(hello)
> hello_escaped
  "%uC548%uB155%uD558%uC138%uC694"
> var hello_unescaped = unescape(hello_escaped)
> hello_unescaped
  "?????"
Run Code Online (Sandbox Code Playgroud)

是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
  "?????"
Run Code Online (Sandbox Code Playgroud)

但是,Mozilla说escape()已被弃用.

虽然encodeURI()和decodeURI()使用上面的utf-8字符串,但docs(以及函数名称本身)告诉我这些方法适用于URI; 我没有看到任何地方提到的utf-8字符串.

简单地说,对于utf-8字符串使用encodeURI()和decodeURI()是否可以?

Sum*_*rve 19

嗨!

说到escapeunescape,我遵守两条规则:

  1. 当你很容易就可以避免它们.
  2. 否则,请使用它们.

当你可以轻松避免它们时:

正如在问题中提到,双方escapeunescape已弃用.通常,应该避免使用已弃用的函数.

所以,如果encodeURIComponent或者encodeURI为你做了诀窍,你应该使用它而不是escape.

当你无法轻易避免它们时使用它们:

浏览器将尽可能地努力实现向后兼容性.所有主要的浏览器已经实现了escapeunescape; 为什么他们不实施它们?

浏览器必须重新定义escape,unescape如果新规范要求它们这样做.可是等等!编写规范的人非常聪明.他们也有兴趣不破坏向后兼容性!

我意识到上述论点很弱.但请相信我,...当涉及到浏览器时,不赞成的东西可行.这甚至包括弃用的HTML标签,如<xmp><center>.

使用escapeunescape:

当然,接下来的问题是,何时使用escapeunescape

近日,在工作时CloudBrave,我不得不处理utf8,latin1并相互转换.

在阅读了大量博客文章后,我意识到这很简单:

var utf8_to_latin1 = function (s) {
    return unescape(encodeURIComponent(s));
};
var latin1_to_utf8 = function (s) {
    return decodeURIComponent(escape(s));
};
Run Code Online (Sandbox Code Playgroud)

这些相互转换,没有使用escape,unescape而是相关的.如果不避免escapeunescape,生活变得更简单.

希望这可以帮助.