Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove backslash escaping from a javascript var?

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?

like image 467
BrunoLM Avatar asked Jul 10 '11 09:07

BrunoLM


People also ask

How do I get rid of backslash?

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.

Does backslash need to be escaped?

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.

How do you escape a backslash in JavaScript?

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.


2 Answers

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.

like image 132
T.J. Crowder Avatar answered Oct 08 '22 11:10

T.J. Crowder


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 ; } 
like image 26
Tony Brix Avatar answered Oct 08 '22 13:10

Tony Brix