How to remove backslash escaping from a javascript var?

Viewed 104868

I have this var

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

Which is

<div class=\"abcdef\">

But I need

<div class="abcdef">

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

8 Answers

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).

Related