如何在 JavaScript 中"re-enable"特殊字符序列?



如果我有一个定义的字符串变量(例如):

 var testString="not\n new line";

它的值当然是notn new line

但是如果直接使用"notn new line",测试字符串将包含新行。

那么,将testString转换为包含新行和所有其他使用双反斜杠"禁用"的特殊字符序列的最简单方法是什么?使用替换?如果它用于unicode字符序列,看起来会花费很多时间。
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"(引号和所有)。

最新更新