473,547 Members | 2,391 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Function to get HTML entities?

Hi,

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 "&lt;"?

Thanks, - Dave
Jul 22 '08 #1
6 1951
laredotornado wrote:
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 "&lt;"?
Well assuming you have script in the browser and HTML document you can
use an approach like this:

function htmlEscape (string) {
var div = document.create Element('div');
div.appendChild (document.creat eTextNode(strin g));
return div.innerHTML;
}

// use like this

htmlEscape('a < b && b c')

// result: a &lt; b &amp;&amp; b &gt; 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/
Jul 22 '08 #2
On Jul 22, 10:42*am, Martin Honnen <mahotr...@yaho o.dewrote:
laredotornadowr ote:
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 "&lt;"?

Well assuming you have script in the browser and HTML document you can
use an approach like this:

function htmlEscape (string) {
* *var div = document.create Element('div');
* *div.appendChil d(document.crea teTextNode(stri ng));
* *return div.innerHTML;

}

// use like this

htmlEscape('a < b && b c')

// result: a &lt; b &amp;&amp; b &gt; 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
Jul 22 '08 #3
laredotornado wrote:
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.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Jul 22 '08 #4
laredotornado wrote:
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 "&lt;"?
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 bugRiddenCrashP ronePieceOfJunk = (
navigator.userA gent.indexOf('M SIE 5') != -1
&& navigator.userA gent.indexOf('M ac') != -1
) // Plone, register_functi on.js:16
Jul 23 '08 #5
Martin Honnen wrote:
laredotornado wrote:
>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 "&lt;"?

Well assuming you have script in the browser and HTML document you can
use an approach like this:

function htmlEscape (string) {
var div = document.create Element('div');
div.appendChild (document.creat eTextNode(strin g));
return div.innerHTML;
}
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
Jul 23 '08 #6
Thomas 'PointedEars' Lahn wrote:
laredotornado wrote:
>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 "&lt;"?

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) + ";";
});
}
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
Jul 23 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1609
by: Frank Thorstens | last post by:
Hi, i have a strange problem and don't know where to look for the bug. Ok, i have an html form witha text area. Very roughly i make something like this (PHP 4.2.3, i can't update the version): ------ $DomDocument = xmldoc('<'.'?xml version=\'1.0\' encoding=\'ISO-8859-1\'?'.'><pages/>');
2
4980
by: micha | last post by:
my php script gets delivered text that contains special chars (like german umlauts), and these chars may, may partially or may not be coverted into html entities already. i don't know beforhand. question: how to spot wether an ampersand is just an ampersand and needs to be converted or is part of an html entity and must be left alone? ...
6
3967
by: Horst Gutmann | last post by:
Hi :-) I currently have quite a big problem with minidom and special chars (for example &uuml;) in HTML. Let's say I have following input file: -------------------------------------------------- <?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html>
4
11746
by: Geoff Wilkins | last post by:
I must confess I only come here when I have a problem - so my apologies if this has been raised before: Using my IE v.6 browser, document.write doesn't convert HTML entities (e.g. &apos;, &amp;) to the appropriate character (though NS 6.2 works fine). Obviously I can get round this for particular entities by writing some code to do the...
11
2196
by: Albretch | last post by:
Hi HTML gurus, I understand that you would use HTML character entities for &auml; and &euro; but why on earth would anyone encode: a colon: ":", a semicolon ";", or a gramatical period "." ?
28
4287
by: Larax | last post by:
Best explanation of my question will be an example, look below at this simple function: function SetEventHandler(element) { // some operations on element element.onclick = function(event) {
8
19799
by: Steven D'Aprano | last post by:
I have a string containing Latin-1 characters: s = u"© and many more..." I want to convert it to HTML entities: result => "&copy; and many more..." Decimal/hex escapes would be acceptable:
6
10130
by: clintonG | last post by:
Can anybody make sense of this crazy and inconsistent results? // IE7 Feed Reading View disabled displays this raw XML <?xml version="1.0" encoding="utf-8" ?> <!-- AT&T HTML entities & XML <elementsare displayed --> <rss version="2.0"> <channel> <title>AT&T HTML entities & XML <elementsare displayed</title> .... <description>
7
4192
by: jeddiki | last post by:
Hi, I am using a function called htmlwrap() which states that it does NOT add a "<br>" to the 70 character line so that it forces a line wrap. ( the script safely wraps long words without destroying html tags which wordwrap has a tendency of doing! )) What I want to do is add that line break so that it DOES force a line wrap - but I am...
0
7510
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7437
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7947
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7463
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
5081
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3493
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3473
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1923
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1050
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.