1

I am using user input inside JavaScript. And of course to be safe my framework is changing some symbols to HTML codes. But for some reason that breaks my JavaScript. So for example this works:

<a onclick="alert('hello')">Hello</a>

But this doesn't:

<a onclick="alert('hel l&#039; lo')">Hello</a>

Why doesn't the below work and how can I make it work?

2 Answers 2

3

&#039; is HTML for '. The HTML is parsed and the result passed to the JavaScript compiler so your JavaScript is alert('hel ' lo') and you can't have an unescaped ' in a string literal delimited with ' characters.

Escaping data to make it safe to insert into HTML is not enough to make it safe to insert into JavaScript which is then inserted into HTML in turn.


Store the user input in a data-* attribute (which is plain HTML so you can use &#039; safely) and then read the attribute from your JavaScript.

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

Comments

2

You're inserting a character reference for a single quote '.

Even though you're using &#039;, when it hits JavaScript, it's a quote mark. Therefore, you're ending the string literal and causing a syntax error.

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.