0

I need the most efficient way to convert all applicable characters to HTML entities.

Two of the solutions I have found on stack overflow are as follow, but one of these involves using DOM and other regular expression.

Using Regular Expression:

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

Using DOM:

function HtmlEncode(s)
{
  var el = document.createElement("div");
  el.innerText = el.textContent = s;
  s = el.innerHTML;
  delete el;
  return s;
}     

Do anyone of you know the efficient solution to convert characters to HTML entities without using any DOM API and regular expression?

Community
  • 1
  • 1
Sam
  • 170
  • 1
  • 2
  • 6
  • 4
    That's like asking how to add numbers without `+`. – SLaks Feb 21 '11 at 12:36
  • 2
    Every character can be converted to an HTML entity; given that you are asking about three characters in particular, I have edited the title of your question. Also, you ask for the "most efficient way" and then rule out two valid ways. Why did you rule out regexp/DOM? Do you not believe that one of them is clearly the mot efficient way? – Phrogz Feb 21 '11 at 13:04
  • 1
    Nop, regular expression are bit slow and interacting with DOM API don't seem to be a good idea. Hence I wanted something different. and yes thanks for editing the title... – Sam Feb 21 '11 at 13:16

2 Answers2

2

Check out the php.JS lib on the link below.

http://phpjs.org/functions/htmlentities:425

Barkermn01
  • 6,781
  • 33
  • 83
  • oh! thanks.... "tmp_str = tmp_str.split(symbol).join(entity);" ... I was missing this part... – Sam Feb 21 '11 at 12:44
0

Coming from the land of "Why on earth would you want to do something like that?"

var foo = "Hello, world";
var html = "";
for (var i = 0; i < foo.length; i++) {
    html += "&#" + foo.charCodeAt(i) + ";";
}
alert(html);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335