简体   繁体   English

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

[英]how to “re-enable” special character sequences in javascript?

If I have a defined String variable as (eg) : 如果我有一个定义的String变量为(例如):

 var testString="not\\n new line";

it's value of course will be not\\n new line . 当然,它的值不会是not\\n new line

But if use directly "not\\n new line" the test string will contain new line. 但是,如果直接使用"not\\n new line"则测试字符串将包含新行。

So what is the easiest way to turn the testString to a string that contains a new line and all other special character sequences that are "disabled" with double backslashes? 那么,最简​​单的方法是将testString转换为包含换行符以及所有其他带有双反斜杠“禁用”的特殊字符序列的字符串吗? Using replaces? 使用替换? It look like it will take a lot of time if it used for unicode characters sequnces. 如果将其用于unicode字符序列,则似乎将花费大量时间。

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

will parse JSON and interpret JSON escape sequences which covers all JS escape sequences except \\x hex, \\v , and the non-standard octal ones. 将解析JSON并解释JSON转义序列,该序列涵盖了所有JS转义序列,但\\x hex, \\v和非标准八进制序列除外。

People will tell you to eval it. 人们会告诉您进行eval Don't. 别。 eval is hugely overpowered for this, and that extra power comes with the risk of XSS vulnerabilities. 为此, 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);
}

If you want to express a string so that Javascript could interpret it (the equivalent of Python's repr function), use JSON.stringify : 如果要表达一个字符串以便Javascript可以解释它 (相当于Python的repr函数),请使用JSON.stringify

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

will result in "not\\n new line" (quotes and all). 将导致“不是\\ n新行”(引号和全部)。

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

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