2

I am doing this

var o = <%- JSON.stringify(object) %>;

in a code with following output

var o = {"_id":"57bafa202acb57b8ab000013","status":"incomplete","title":"<script>alert(1);</script>","updated_at":"2016-08-22T18:42:00+05:30","id":"57bafa202acb57b8ab000013"};

and the following error.

Uncaught SyntaxError: Invalid or unexpected token

There is a title attribute with a "<script>alert(1);</script>" in the object. How do I deal with this?

2
  • When does the error occur? Clearly the JSON.stringify is not failing if you have that output. Commented Aug 22, 2016 at 16:53
  • Its failing at this line itself. JSON.stringify works fine. var o = <%- JSON.stringify(object) %>; Commented Aug 22, 2016 at 16:58

1 Answer 1

2

You need to replace the <'s, for instance by using a Unicode escape:

var o = <%- JSON.stringify(object).replace(/</g, '\\u003c') %>;
Sign up to request clarification or add additional context in comments.

2 Comments

That worked. Would you suggest any other characters apart from < and > that should be escaped with unocode? Also how does this work but the above code doesn't. var a = {"title":"<script>alert(1);</script>"}; JSON.parse(JSON.stringify(a))
The & would be a good candidate as well. The main issue is that you're mixing HTML with JS, and both have their own set of special characters. For HTML, </, even in JS code, starts the end of an element.

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.