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?
To remove all backslashes from a string:Call the replaceAll method, passing it a string containing 2 backslashes as the first parameter and an empty string as the second - str. replaceAll('\\', '') . The replaceAll method returns a new string with all of the matches replaced.
Control character But escape characters used in programming (such as the backslash, "\") are graphic, hence are not control characters. Conversely most (but not all) of the ASCII "control characters" have some control function in isolation, therefore they are not escape characters.
The backslash() is an escape character in JavaScript. The backslash \ is reserved for use as an escape character in JavaScript. To escape the backslash in JavaScript use two backslashes.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With