Escape/ Unescape HTML?

P

Philipp

How do I convert a string to escaped HTML? (Let's say I'm not using
DOM.) E.g. "<p>foo</p>" would become "&lt;p&gt;foo&lt;/p&gt;"?

Reversely, how do I unescape a string to be HTML? E.g. "&lt;em&gt;"
would turn back into "<em>".

I mean a function like the following would do the job but is there a
more JS-native solution?

html = html.replace(/&/g, "&amp;");
html = html.replace(/</g, "&lt;");
html = html.replace(/>/g, "&gt;");
html = html.replace(/"/g, "&quot;");

Thanks!
 
E

Evertjan.

Philipp wrote on 20 dec 2007 in comp.lang.javascript:
How do I convert a string to escaped HTML? (Let's say I'm not using
DOM.) E.g. "<p>foo</p>" would become "&lt;p&gt;foo&lt;/p&gt;"?

Reversely, how do I unescape a string to be HTML? E.g. "&lt;em&gt;"
would turn back into "<em>".
I mean a function like the following would do the job but is there a
more JS-native solution?

Ever tried asking the natives? Oh you just did. ;-)

s = unescape(s);

the below is not unescape, but escape-ish:
 
T

Thomas 'PointedEars' Lahn

Philipp said:
How do I convert a string to escaped HTML? (Let's say I'm not using
DOM.) E.g. "<p>foo</p>" would become "&lt;p&gt;foo&lt;/p&gt;"?

Reversely, how do I unescape a string to be HTML? E.g. "&lt;em&gt;"
would turn back into "<em>".

I mean a function like the following would do the job but is there a
more JS-native solution?

html = html.replace(/&/g, "&amp;");
html = html.replace(/</g, "&lt;");
html = html.replace(/>/g, "&gt;");
html = html.replace(/"/g, "&quot;");

`"' does not need to be escaped, however if this is what you are looking
for, then

function escapeHTML(s)
{
return s.replace(
/[&<>"]/g,
function(m)
{
var map = {
"&": "amp",
"<": "lt",
">": "gt",
'"': "quot"
};

return "&" + map[m] + ";";
});
}

and

function unescapeHTML()
{
return s.replace(
/&(amp|[lg]t|quot);/g,
function(m, p1)
{
var map = {
amp: "&",
lt: "<",
gt: ">",
quot: '"'
};

return map[p1];
});
}

may very well be the answer.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,016
Latest member
TatianaCha

Latest Threads

Top