Html entities must be encoded in alt attribute of an image in HTML page. So
<img id="formula" alt="A → B" src="formula.png" />
will work well.
On the other hand, the same JavaScript code will not work
document.getElementById('formula').alt = 'A → B';
and will produce A → B instead of A → B.
How to do it through JavaScript, when it is not possible to put the special (unencoded) characters in the source code?
Html entities must be encoded in alt attribute of an image in HTML page. So
<img id="formula" alt="A → B" src="formula.png" />
will work well.
On the other hand, the same JavaScript code will not work
document.getElementById('formula').alt = 'A → B';
and will produce A → B instead of A → B.
How to do it through JavaScript, when it is not possible to put the special (unencoded) characters in the source code?
Share Improve this question edited May 23, 2017 at 10:33 CommunityBot 11 silver badge asked May 5, 2010 at 17:13 Arseni MourzenkoArseni Mourzenko 52.3k35 gold badges118 silver badges210 bronze badges 1- Google peoples - see also: stackoverflow./questions/94037/… – Andrew Commented Jun 21, 2017 at 20:57
4 Answers
Reset to default 8JavaScript has its own system for escaping special characters in strings:
document.getElementById('formula').alt = 'A \u2192 B';
Here's an alternative if you can't save your file using a Unicode format:
function decodeHTML(str) {
return str.replace(/&#(\d+);?/g, function() {
return String.fromCharCode(arguments[1])
});
}
However, this requires you to use the numeric representation. In this case →
.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Decode HTML entities using JavaScript</title>
</head>
<body>
<img id="formula" src="vote-arrow-up-on.png" alt="A → C">
<script>
function html_entity_decode(str) {
var p = document.createElement("p");
p.innerHTML = str.replace(/</g,"<").replace(/>/g,">");
return p.innerHTML;
}
var theValue = html_entity_decode('A → B');
document.getElementById('formula').title = theValue;
</script>
</body>
</html>
Credits to The JavaScript Source.
EDIT: I changed the original code to only use innerHTML
on a <p>
element, instead of innerHTML
and value
of a <textarea>
.
In that particular case, you don't have encode special HTML characters in JavaScript.
The W3C validator should not plain about this (just tested it) and the document should validate. If not post your code and I'll update my answer.