5

I am using to parse 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>"');
1

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

This is an interesting (and effective) approach, but are there still considerations for using eval safely (see: When is JavaScript's eval() not evil?. Also, your regex is loose enough to capture any " quoted string. If that is desired, you could get away with /"[^"]+"/g; but if you want to limit it to strings that contain a backslash, you should use a pattern similar to /"[^"]*\\+[^"]*"/g
0

The most idiotic way would be.

"<div class=\\'shows\\'>\\\\n<\\/div>".replace(/\\n/g, '').replace(/\\/g, '');
// "<div class='shows'></div>"

Smarter way would be to first unescape \n's than check with regex if there are unescaped matches, and than escape those as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.