How do I escape a single quote ( ‘ ) in JavaScript? [duplicate]

You should always consider what the browser will see by the end. In this case, it will see this:

<img src="https://stackoverflow.com/questions/16134910/something" onmouseover="change(" ex1')' />

In other words, the “onmouseover” attribute is just change(, and there’s another “attribute” called ex1')' with no value.

The truth is, HTML does not use \ for an escape character. But it does recognise &quot; and &apos; as escaped quote and apostrophe, respectively.

Armed with this knowledge, use this:

document.getElementById("https://stackoverflow.com/questions/16134910/something").innerHTML = "<img src="https://stackoverflow.com/questions/16134910/something" onmouseover="change(&quot;ex1&quot;)" />";

… That being said, you could just use JavaScript quotes:

document.getElementById("https://stackoverflow.com/questions/16134910/something").innerHTML = "<img src="https://stackoverflow.com/questions/16134910/something" onmouseover="change(\"ex1\")" />";

Leave a Comment