如何";“重新启用”;javascript中的特殊字符序列?

如何";“重新启用”;javascript中的特殊字符序列?,javascript,string,Javascript,String,如果我将字符串变量定义为(例如): 它的值当然将是而不是\n新行 但是如果直接使用“not\n new line”,测试字符串将包含新行 那么,将测试字符串转换为包含新行和所有其他使用双反斜杠“禁用”的特殊字符序列的字符串的最简单方法是什么? 使用替换?如果将其用于unicode字符sequencs,看起来需要花费很多时间 JSON.parse('"' + testString + '"') 将解析JSON并解释JSON转义序列,该转义序列涵盖除十六进制、\v和非标准八进制转义序列之外的所有J

如果我将字符串变量定义为(例如):

它的值当然将是
而不是\n新行

但是如果直接使用
“not\n new line”
,测试字符串将包含新行

那么,将测试字符串转换为包含新行和所有其他使用双反斜杠“禁用”的特殊字符序列的字符串的最简单方法是什么? 使用替换?如果将其用于unicode字符sequencs,看起来需要花费很多时间

JSON.parse('"' + testString + '"')
将解析JSON并解释JSON转义序列,该转义序列涵盖除十六进制、
\v
和非标准八进制转义序列之外的所有JS转义序列

人们会告诉你评估它。不要
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);
}
将解析JSON并解释JSON转义序列,该转义序列涵盖除十六进制、
\v
和非标准八进制转义序列之外的所有JS转义序列

人们会告诉你评估它。不要
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="not\n new line";
console.log(JSON.stringify(testString))

将导致“not\n new line”(引号和全部)。

如果要表达字符串以便Javascript能够解释它(相当于Python的
repr
函数),请使用
JSON。stringify

var testString="not\n new line";
console.log(JSON.stringify(testString))

将导致“not\n new line”(引号和全部)。

您的
decodeJsString
似乎可以工作:-)(将使用unicode字符对其进行测试,我需要一些时间才能理解)。JSON对IE9不起作用…您的
decodeJsString
似乎可以工作:-)(将使用unicode字符进行测试,我需要一些时间来理解它)。JSON对IE9不起作用……为什么是向下投票?为什么是向下投票?