Reputation: 326
How can I unescape a string like this in JavaScript
alert(\"Testing\");\nconsole.log(\"Hello\");
so that is is escaped to this:
alert("Testing");
console.log("Hello");
I have a program which uses an api and returns the escaped string, but I want to replace the escaped version of the string with the literal representation, e.g. "\n" with a newline. I saw a question, which had this code to escape a string, but it did not say how to undo the operation, to better understand how the string is escaped here is the function in question which escapes a string:
function addslashes(string) {
return string.replace(/\\/g, '\\\\').
replace(/\u0008/g, '\\b').
replace(/\t/g, '\\t').
replace(/\n/g, '\\n').
replace(/\f/g, '\\f').
replace(/\r/g, '\\r').
replace(/'/g, '\\\'').
replace(/"/g, '\\"');
}
I pretty much want to undo that. Thanks in advance!
Turns out I can do something like this:
var string = "<!DOCTYPE html><script>alert(\"Hello\");<\/html>"
console.log(unescape(escape(string)));
Upvotes: -1
Views: 1367
Reputation: 6306
As this is the first hit on Google for unescaping backslashed characters in JavaScript, here's a function that should undo JavaScript's literal escaping:
const unescapeBackslashes = s => s.replaceAll("\\'", "\'").replaceAll('\\"', '\"').replaceAll('\\n', '\n').replaceAll('\\r', '\r')
.replaceAll('\\t', '\t').replaceAll('\\b', '\b').replaceAll('\\f', '\f').replaceAll('\\v', '\v')
.replace(/\\x([0-9A-Fa-f]{2})/g, (match, code) => String.fromCharCode(parseInt(code, 16)))
.replace(/\\[0-3]([0-7]{1,2})/g, (match, code) => String.fromCharCode(parseInt(code, 8)))
.replaceAll('\\', '');
E.g.
> str = 'alert(\\"Testing\\");\\nconsole.log(\\"Hello\\");'
> console.log(unescapeBackslashes(str))
alert("Testing");
console.log("Hello");
Upvotes: -1
Reputation: 613
There's a built in unescape() function you can use
const unescaped = unescape(`alert(\"Testing\");\nconsole.log(\"Hello\");`);
console.log(unescaped)
Here's an alternative answer that undoes the specific encoding you did
const escapedString = `alert(\"Testing\");\nconsole.log(\"Hello\");`
function removeSlashes(string) {
return string.replace('\\\\', /\\/g).
replace('\\b', /\u0008/g).
replace('\\t', /\t/g).
replace('\\n', /\n/g).
replace('\\f', /\f/g).
replace('\\r', /\r/g).
replace('\\\'', /'/g).
replace('\\"', /"/g);
}
console.log(removeSlashes(escapedString));
Upvotes: -1