开发者

How to remove backslash escaping from a javascript var?

开发者 https://www.devze.com 2023-03-18 23:36 出处:网络
I have this var var x = \"<div class=\\\\\\\"abcdef\\\\\\\">\"; Which is <div class=\\\"abcdef\\\">

I have this var

var x = "<div class=\\\"abcdef\\\">";

Which is

<div class=\"abcdef\">

But I开发者_StackOverflow need

<div class="abcdef">

How can I "unescape" this var to remove all escaping characters?


You can replace a backslash followed by a quote with just a quote via a regular expression and the String#replace function:

var x = "<div class=\\\"abcdef\\\">";
x = x.replace(/\\"/g, '"');
document.body.appendChild(
  document.createTextNode("After: " + x)
);

Note that the regex just looks for one backslash; there are two in the literal because you have to escape backslashes in regular expression literals with a backslash (just like in a string literal).

The g at the end of the regex tells replace to work throughout the string ("global"); otherwise, it would replace only the first match.


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(/(^|[^\\])(\\\\)*\\$/, "$&\\");

  // escape unescaped double quotes to prevent error with
  // added double quotes in json string
  parsedStr = parsedStr.replace(/(^|[^\\])((\\\\)*")/g, "$1\\$2");

  try {
    parsedStr = JSON.parse(`"${parsedStr}"`);
  } catch(e) {
    return str;
  }
  return parsedStr ;
}


If you want to remove backslash escapes, but keep escaped backslashes, here's what you can do:

"a\\b\\\\c\\\\\\\\\\d".replace(/(?:\\(.))/g, '$1');

Results in: ab\c\\d.

Explanation of replace(/(?:\\(.))/g, '$1'):

/(?:\\) is a non-capturing group to capture the leading backslash

/(.) is a capturing group to capture what's following the backslash

/g global matching: Find all matches, not just the first.

$1 is referencing the content of the first capturing group (what's following the backslash).


Try this:

x = x.replace(/\\/g, "");


var x = "<div class=\\\"abcdef\\\">";
alert(x.replace(/\\/gi, ''));


'<div class=\\\"abcdef\\\">'.replace(/\\\"/g, '"')

Other answers have you delete all backslashes, you only want to delete the ones befoew the quotes.


You need to make there be one backslash instead of three.
Like this:

var x = "<div class=\"abcdef\">";        


Let me propose this variant:

function un(v) { eval('v = "'+v+'"'); return v; }

This function will not simply remove slashes. Text compiles as code, and in case correct input, you get right unescaping result for any escape sequence.

0

精彩评论

暂无评论...
验证码 换一张
取 消