如果我有一个定义的字符串变量(例如):
var testString="not\n new line";
它的值当然是notn new line
但是如果直接使用"notn new line"
,测试字符串将包含新行。
JSON.parse('"' + testString + '"')
将解析JSON并解释JSON转义序列,包括除了x
十六进制,v
和非标准八进制之外的所有JS转义序列。
人们会告诉你去eval
它。不喜欢。eval
在这方面是非常强大的,而额外的功能伴随着XSS漏洞的风险。
var jsEscapes = {
'n': 'n',
'r': 'r',
't': 't',
'f': 'f',
'v': 'v',
'b': 'b'
};
function decodeJsEscape(_, hex0, hex1, octal, other) {
var hex = hex0 || hex1;
if (hex) { return String.fromCharCode(parseInt(hex, 16)); }
if (octal) { return String.fromCharCode(parseInt(octal, 8)); }
return jsEscapes[other] || other;
}
function decodeJsString(s) {
return s.replace(
// Matches an escape sequence with UTF-16 in group 1, single byte hex in group 2,
// octal in group 3, and arbitrary other single-character escapes in group 4.
/\(?:u([0-9A-Fa-f]{4})|x([0-9A-Fa-f]{2})|([0-3][0-7]{0,2}|[4-7][0-7]?)|(.))/g,
decodeJsEscape);
}
如果你想表达字符串以便Javascript能够解释它(相当于Python的repr
函数),请使用JSON.stringify
:
var testString="notn new line";
console.log(JSON.stringify(testString))
将导致"notn new line"(引号和所有)。