How to remove backslash escaping from a javascript var?

后端 未结 8 984
轮回少年
轮回少年 2020-12-09 01:58

I have this var

var x = \"
\";

Which is

8条回答
  •  长情又很酷
    2020-12-09 02:43

    You can use JSON.parse to unescape slashes:

    function unescapeSlashes(str) {
      // add another escaped slash if the string ends with an odd
      // number of escaped slashes which will crash JSON.parse
      let parsedStr = str.replace(/(^|[^\\])(\\\\)*\\$/, "$&\\");
    
      try {
        parsedStr = JSON.parse(`"${parsedStr}"`);
      } catch(e) {
        return str;
      }
      return parsedStr ;
    }
    

提交回复
热议问题