Javascript \\x escaping

纵饮孤独 提交于 2019-11-29 10:56:48
arcyqwerty

If you have a string that you want escaped, you can use String.prototype.charCodeAt()

If you have the code with escapes, you can just evaluate them to get the original string. If it's a string with literal escapes, you can use String.fromCharCode()

  • If you have '\x32\x20\x60\x78\x6e\x7a\x9c\x89' and want "2 `xnz" then

    '\x32\x20\x60\x78\x6e\x7a\x9c\x89' == "2 `xnz"
    
  • If you have '\\x32\\x20\\x60\\x78\\x6e\\x7a\\x9c\\x89' which is a literal string with the value \x32\x20\x60\x78\x6e\x7a\x9c\x89 then you can parse it by passing the decimal value of each pair of hex digits to String.prototype.fromCharCode()

    '\\x32\\x20\\x60\\x78\\x6e\\x7a\\x9c\\x89'.replace(/\\x([0-9a-f]{2})/g, function(_, pair) {
      return String.fromCharCode(parseInt(pair, 16));
    })
    

    Alternatively, eval is an option if you can be sure of the safety of the input and performance isn't important1.

    eval('"\\x32\\x20\\x60\\x78\\x6e\\x7a\\x9c\\x89"')
    

    Note the " nested in the ' surrounding the input string.

    If you know it's a program, and it's from a trusted source, you can eval the string directly, which won't give you the ASCII, but will execute the program itself.

    eval('\\x32\\x20\\x60\\x78\\x6e\\x7a\\x9c\\x89')
    

    Note that the input you provided is not a program and the eval call fails.

  • If you have "2 `xnz" and want '\x32\x20\x60\x78\x6e\x7a\x9c\x89' then

    "2 `xnz".split('').map(function(e) {
      return '\\x' + e.charCodeAt(0).toString(16);
    }).join('')
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!