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.
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 ;
}
You need to make there be one backslash instead of three. Like this:
var x = "
";
answered Dec 29, 2013 at 14:11
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.
answered Feb 11, 2013 at 21:53
2
How do I remove an escape character from a string?
JSON Escape / Unescape.
Backspace is replaced with \b..
Form feed is replaced with \f..
Newline is replaced with \n..
Carriage return is replaced with \r..
Tab is replaced with \t..
Double quote is replaced with \".
Backslash is replaced with \\.
How do you escape a backward slash 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.
How do you remove slashes from a string?
Use the String.replace() method to remove a trailing slash from a string, e.g. str. replace(/\/+$/, '') . The replace method will remove the trailing slash from the string by replacing it with an empty string.
What are escape characters in regex?
The \ is known as the escape code, which restore the original literal meaning of the following character. Similarly, * , + , ? (occurrence indicators), ^ , $ (position anchors) have special meaning in regex. You need to use an escape code to match with these characters.