44

Possible Duplicate:
How to escape HTML

How can a string be converted to HTML in JavaScript?

e.g.

var unsafestring = "<oohlook&atme>";
var safestring = magic(unsafestring);

where safestring now equals "&lt;ohhlook&amp;atme&gt;"

I am looking for magic(...). I am not using JQuery for magic.

Community
  • 1
  • 1
James
  • 25,427
  • 16
  • 78
  • 101

5 Answers5

70
function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

So then with var unsafestring = "<oohlook&atme>"; you would use htmlEntities(unsafestring);

j08691
  • 190,436
  • 28
  • 232
  • 252
36

If you want to use a library rather than doing it yourself:

The most commonly used way is using jQuery for this purpose:

var safestring = $('<div>').text(unsafestring).html();

If you want to to encode all the HTML entities you will have to use a library or write it yourself.

You can use a more compact library than jQuery, like HTML Encoder and Decode

gdoron is supporting Monica
  • 136,782
  • 49
  • 273
  • 342
33

Do not bother with encoding. Use a text node instead. Data in text node is guaranteed to be treated as text.

document.body.appendChild(document.createTextNode("Your&funky<text>here"))
Oleg V. Volkov
  • 19,811
  • 3
  • 40
  • 60
14

You need to escape < and &. Escaping > too doesn't hurt:

function magic(input) {
    input = input.replace(/&/g, '&amp;');
    input = input.replace(/</g, '&lt;');
    input = input.replace(/>/g, '&gt;');
    return input;
}

Or you let the DOM engine do the dirty work for you (using jQuery because I'm lazy):

function magic(input) {
    return $('<span>').text(input).html();
}

What this does is creating a dummy element, assigning your string as its textContent (i.e. no HTML-specific characters have side effects since it's just text) and then you retrieve the HTML content of that element - which is the text but with special characters converted to HTML entities in cases where it's necessary.

ThiefMaster
  • 285,213
  • 77
  • 557
  • 610
-5

The only character that needs escaping is <. (> is meaningless outside of a tag).

Therefore, your "magic" code is:

safestring = unsafestring.replace(/</g,'&lt;');
Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540