How to remove backslash escaping from a javascript var?

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.

Leave a Comment