Is there a Javascript way of taking a string of text and encoding it
such that its HTML entities are represented? For example, "<" would
be represented as "<"?
Thanks, - Dave
Well assuming you have script in the browser and HTML document you can
use an approach like this:
function htmlEscape (string) {
var div = document.createElement('div');
div.appendChild(document.createTextNode(string));
return div.innerHTML;
}
// use like this
htmlEscape('a < b && b > c')
// result: a < b && b > c
There are however lots of HTML entities defined in the HTML 4 DTD that
the above approach does not cover. So it depends on which characters
exactly you want to replace with entity references.
--
Martin Honnen
http://JavaScript.FAQTs.com/
Thanks for this excellent function, Martin. Just so the state of the
world is the same as when I entered it, how do I remove the div I
just created from the existing DOM after I get the HTML vals?
- Dave
> Thanks for this excellent function, Martin. Just so the state of the
> world is the same as when I entered it, how do I remove the div I
> just created from the existing DOM after I get the HTML vals?
The div element object is created inside the function but never inserted
anywhere in the document so there is no need to remove it from the document.
The most efficient, reliable and easy to maintain way nowadays is probably
function htmlEncode(s)
{
return s.replace(
/[<>&]/g,
function(m) {
return "&" + m.charCodeAt(0) + ";";
});
}
PointedEars
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16
This rather bloated, inefficient, and unreliable approach mixes proprietary
and standards-compliant features without previous runtime feature test. It
can be safely recommended against.
PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
Supplemental: This does not meet the described outcome exactly, but it works
anyway (sometimes even better than character entity references) and can
easily be extended for other characters.
PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann