52

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
  • 30,496
  • 19
  • 86
  • 113

5 Answers5

79
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
  • 204,283
  • 31
  • 260
  • 272
40

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
  • 147,333
  • 58
  • 291
  • 367
  • 15
    This requires jQuery which a) the question isn't tagged with and b) isn't needed. – j08691 Jan 02 '13 at 22:12
  • 3
    @j08691, Yes, I noticed the missing tag, it still doesn't say it's not the best option, cuz he will need a library, and the most powerful js lib can do that as well. – gdoron Jan 02 '13 at 22:13
  • 4
    Agree with @j08691, it works but it's just a heavy workaround. Why the upvotes? – Christophe Jan 02 '13 at 22:21
  • @Christophe, though it was an old comment. People upvote when something helped them. – gdoron Sep 27 '16 at 18:41
38

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
  • 21,719
  • 4
  • 44
  • 68
16

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
  • 310,957
  • 84
  • 592
  • 636
-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
  • 320,036
  • 81
  • 464
  • 592