Skip to content Skip to sidebar Skip to footer

How To "re-enable" Special Character Sequences In Javascript?

If I have a defined String variable as (e.g.) : var testString='not\\n new line'; it's value of course will be not\n new line. But if use directly 'not\n new line' the test strin

Solution 1:

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.

People will tell you to eval it. Don't. eval is hugely overpowered for this, and that extra power comes with the risk of XSS vulnerabilities.

var jsEscapes = {
  'n': '\n',
  'r': '\r',
  't': '\t',
  'f': '\f',
  'v': '\v',
  'b': '\b'
};

functiondecodeJsEscape(_, hex0, hex1, octal, other) {
  var hex = hex0 || hex1;
  if (hex) { returnString.fromCharCode(parseInt(hex, 16)); }
  if (octal) { returnString.fromCharCode(parseInt(octal, 8)); }
  return jsEscapes[other] || other;
}

functiondecodeJsString(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);
}

Solution 2:

If you want to express a string so that Javascript could interpret it (the equivalent of Python's repr function), use JSON.stringify:

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

will result in "not\n new line" (quotes and all).

Post a Comment for "How To "re-enable" Special Character Sequences In Javascript?"