I am trying to use a string that contains double quotes in the title attribute of an anchor. So far I tried these:
<a href=".." title="Some \"text\"">Some text</a>
<!-- The title looks like `Some \` --!>
and
<a href=".." title="Some "text"">Some text</a>
<!-- The title looks like `Some ` --!>
Please note that using single quotes is not an option.
There is at least one situation where using single quotes will not work and that is if you are creating the markup "on the fly" from JavaScript. You use single quotes to contain the string and then any property in the markup can have double quotes for its value.
It may work with any character from the HTML Escape character list, but I had the same problem with a Java project. I used StringEscapeUtils.escapeHTML("Testing \" <br> <p>")
and the title was <a href=".." title="Test" <br> <p>">Testing</a>
.
It only worked for me when I changed the StringEscapeUtils to StringEscapeUtils.escapeJavascript("Testing \" <br> <p>")
and it worked in every browser.
Here's a snippet of the HTML escape characters taken from a cached page on archive.org:
< | < less than sign
@ | @ at sign
] | ] right bracket
{ | { left curly brace
} | } right curly brace
… | … ellipsis
‡ | ‡ double dagger
’ | ’ right single quote
” | ” right double quote
– | – short dash
™ | ™ trademark
¢ | ¢ cent sign
¥ | ¥ yen sign
© | © copyright sign
¬ | ¬ logical not sign
° | ° degree sign
² | ² superscript 2
¹ | ¹ superscript 1
¼ | ¼ fraction 1/4
¾ | ¾ fraction 3/4
÷ | ÷ division sign
” | ” right double quote
> | > greater than sign
[ | [ left bracket
` | ` back apostrophe
| | | vertical bar
~ | ~ tilde
† | † dagger
‘ | ‘ left single quote
“ | “ left double quote
• | • bullet
— | — longer dash
¡ | ¡ inverted exclamation point
£ | £ pound sign
¦ | ¦ broken vertical bar
« | « double left than sign
® | ® registered trademark sign
± | ± plus or minus sign
³ | ³ superscript 3
» | » double greater-than sign
½ | ½ fraction 1/2
¿ | ¿ inverted question mark
“ | “ left double quote
— | — dash
The escape code "
can also be used instead of "
.
Using "
is the way to do it. I tried your second code snippet, and it works in both Firefox and Internet Explorer.
Perhaps you can use JavaScript to solve your cross-browser problem. It uses a different escape mechanism, one with which you're obviously already familiar:
(reference-to-the-tag).title = "Some \"text\"";
It doesn't strictly separate the functions of HTML, JavaScript, and CSS the way folks want you to nowadays, but whom do you need to make happy? Your users or techies you don't know?
Source: Stackoverflow.com