简体   繁体   中英

Unescape an escaped string in JavaScript

I'm running a loop to display characters of a specific Unicode escape sequence.

var es = '';

for (var i = 0; i <= 9999; i++) {
  if (i < 10) {
    es = '\\u000' + i;
  } else if (i < 100) {
    es = '\\u00' + i;
  } else {
    es = '\\u' + i;
  }
  console.log(es);
}

...however, it doesn't display the characters, just the sequence. Is there anyway in JavaScript to unescape the escaped sequence to force it show the character?

To do this, you'll want to use String.fromCharCode()

var es = '';
for (var i = 0; i < 9999; ++i) {
  es = String.fromCharCode(i);
  // ...
}

The \\uNNNN syntax only works with constant values inside the larger string constant.

edit — an important comment below points out that due to the problematic UTF-16 implementation of JavaScript strings, .fromCharCode() has problems with characters outside the Basic Multilingual Plane. For that, the ES6 (ES2015) has String.fromCodePoint() , a similar function that does handle "astral" characters outside the 16-bit range. More on that here and in the link in the comment.

For anyone stumbling across this question (most likely my future self) looking to "unescape" a previously escaped Javascript special characters , here's a hacky way to do it:

newString = JSON.stringify(string).slice(1,-1)

However this seems to only work for certain characters, like \\t , \\n , \\r , \\f , \\b , \\\\ , etc.

To explain myself better, in the case of tabs, this will convert a tab character back into literal/raw string that is \\t .

我遇到了来自 REST 端点的 JSON 响应的类似问题,这解决了它:

JSON.parse('"' + string + '"')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM