0

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!

Edit

Turns out I can do something like this:

var string = "<!DOCTYPE html><script>alert(\"Hello\");<\/html>"
console.log(unescape(escape(string)));
      
Explosion
  • 328
  • 2
  • 10
  • Why do you need to do this? Have you tried directly displaying the string? – Unmitigated Jan 08 '21 at 18:40
  • In my specific case I am making a bookmarklet that beautifies the selected code in any textarea. My API that I made returns an escaped string that I need to unescape. – Explosion Jan 08 '21 at 18:42

1 Answers1

0

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));
FoundingBox
  • 580
  • 2
  • 7