简体   繁体   English

在 JavaScript 中取消转义转义字符串

[英]Unescape an escaped string in JavaScript

I'm running a loop to display characters of a specific Unicode escape sequence.我正在运行一个循环来显示特定 Unicode 转义序列的字符。

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?无论如何在 JavaScript 中是否有转义转义序列以强制它显示字符?

To do this, you'll want to use String.fromCharCode()为此,您需要使用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. \\uNNNN语法仅适用于较大字符串常量内的常量值。

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.编辑——下面的一条重要评论指出,由于 JavaScript 字符串的 UTF-16 实现有问题, .fromCharCode()存在基本多语言平面之外的字符问题。 For that, the ES6 (ES2015) has String.fromCodePoint() , a similar function that does handle "astral" characters outside the 16-bit range.为此,ES6 (ES2015) 具有String.fromCodePoint() ,这是一个类似的函数,可以处理 16 位范围之外的“星体”字符。 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:对于任何在这个问题上绊倒的人(很可能是我未来的自己)希望“取消转义”以前转义的Javascript special characters ,这是一种hacky方法:

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

However this seems to only work for certain characters, like \\t , \\n , \\r , \\f , \\b , \\\\ , etc.然而,这似乎只适用于某些字符,如\\t\\n\\r\\f\\b\\\\等。

To explain myself better, in the case of tabs, this will convert a tab character back into literal/raw string that is \\t .为了更好地解释自己,在制表符的情况下,这会将制表符转换回文字/原始字符串\\t

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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