Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unescape JavaScript string literal value?

I am using regex to parse javascript code (using an ES parser, such as Esprima, is not an option for technical environment limitations).

The subject code (the code being parsed is):

(function() {
    $('#3bf779cd').replaceWith("<div class=\'shows\'>\n<\/div>");

    window.fadeItems();
}).call(this);

The value I am interested in is the first parameter of replaceWith, which is a string literal. I am getting this variable using regex:

const subjectValue = subjectCode.match(/\.replaceWith\(((["'])(?:(?=(\\?))\3.)*?\2)/m)[1].slice(1, -1);

console.log(subjectValue);

The output of this is:

<div class=\'shows\'>\n<\/div>

How do I escape subjectValue in a way that the output would be:

<div class='shows'>
</div>

Simply using unescape has no effect.

If I am not mistaken, the question comes does to how to unescape this value:

console.log('"<div class=\\\'shows\\\'>\\\\n<\\\/div>"');
like image 361
Gajus Avatar asked Oct 30 '22 08:10

Gajus


1 Answers

You're looking for eval (yes you heard correctly):

text = document.querySelector('script').textContent;

dqString = /"(\\.|[^"])*"/g

s = text.match(dqString)[0]

raw = eval(s);

alert(raw);
<script>
(function() {
    $('#3bf779cd').replaceWith("<div class=\'shows\'>\n<\/div>");
    window.fadeItems();
});
</script>
like image 186
georg Avatar answered Nov 09 '22 22:11

georg