We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
No escaping is used with single quotes. Use a double backslash as the escape character for backslash.
To escape a single or double quote in a string, use a backslash \ character before each single or double quote in the contents of the string, e.g. 'that\'s it' . Copied!
' End first quotation which uses single quotes. " Start second quotation, using double-quotes. ' Quoted character. " End second quotation, using double-quotes.
You should always consider what the browser will see by the end. In this case, it will see this:
<img src='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 "
and '
as escaped quote and apostrophe, respectively.
Armed with this knowledge, use this:
document.getElementById("something").innerHTML = "<img src='something' onmouseover='change("ex1")' />";
... That being said, you could just use JavaScript quotes:
document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";
The answer here is very simple:
You're already containing it in double quotes, so there's no need to escape it with \
.
If you want to escape single quotes in a single quote string:
var string = 'this isn\'t a double quoted string';
var string = "this isn\"t a single quoted string";
// ^ ^ same types, hence we need to escape it with a backslash
or if you want to escape \'
, you can escape the bashslash to \\
and the quote to \'
like so:
var string = 'this isn\\\'t a double quoted string';
// vvvv
// \ ' (the escaped characters)
However, if you contain the string with a different quote type, you don't need to escape:
var string = 'this isn"t a double quoted string';
var string = "this isn't a single quoted string";
// ^ ^ different types, hence we don't need escaping
You can escape a '
in JavaScript like \'
Since the values are actually inside of an HTML attribute, you should use '
"<img src='something' onmouseover='change('ex1')' />";
document.getElementById("something").innerHTML = "<img src=\"something\" onmouseover=\"change('ex1')\" />";
OR
document.getElementById("something").innerHTML = '<img src="something" onmouseover="change(\'ex1\')" />';
It should be working...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With