使用 JSON.decode
有明显的缺点,您必须了解这些缺点:
- 您必须将字符串用双引号括起来
- 许多字符不受支持,必须自行转义。例如,即使以下所有内容都有效,将它们包装在双引号中,并将其传递给
JSON.decode
将导致错误:\\n
、\n
、\\0
、a"a
- 它不支持十六进制转义:
\\x45
- 它不支持 Unicode 代码点序列:
\\u{045}
还有其他注意事项。基本上,为此目的使用 JSON.decode
是一种 hack 并且无法如您所预期的那样工作。您应该坚持使用 JSON
库处理 JSON,而不是进行字符串操作。
我最近自己遇到了这个问题并希望获得一个强大的解码器,所以我最终编写了一个。它是完整和经过全面测试的,可以在这里找到:https://github.com/iansan5653/unraw。它尽可能地模仿了 JavaScript 标准。
解释:
源代码大约有 250 行,所以我不会在这里包含全部内容,但基本上它使用以下正则表达式查找所有转义序列,然后使用 parseInt(string, 16)
解码基于十六进制的数字,再使用 String.fromCodePoint(number)
获得相应的字符:
/\\(?:(\\)|x([\s\S]{0,2})|u(\{[^}]*\}?)|u([\s\S]{4})\\u([^{][\s\S]{0,3})|u([\s\S]{0,4})|([0-3]?[0-7]{1,2})|([\s\S])|$)/g
注释(注意:此正则表达式匹配所有转义序列,包括无效的。如果字符串在JS中会引发错误,则在我的库中也会引发错误[即,'\x!!'
将导致错误]):
/
\\ # All escape sequences start with a backslash
(?: # Starts a group of 'or' statements
(\\) # If a second backslash is encountered, stop there (it's an escaped slash)
| # or
x([\s\S]{0,2}) # Match valid hexadecimal sequences
| # or
u(\{[^}]*\}?) # Match valid code point sequences
| # or
u([\s\S]{4})\\u([^{][\s\S]{0,3}) # Match surrogate code points which get parsed together
| # or
u([\s\S]{0,4}) # Match non-surrogate Unicode sequences
| # or
([0-3]?[0-7]{1,2}) # Match deprecated octal sequences
| # or
([\s\S]) # Match anything else ('.' doesn't match newlines)
| # or
$ # Match the end of the string
) # End the group of 'or' statements
/g # Match as many instances as there are
示例
使用该库:
import unraw from "unraw";
let step1 = unraw('http\\u00253A\\u00252F\\u00252Fexample.com');
let step2 = decodeURIComponent(step1);