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.

4
  • 2
    You could just append a document.createTextNode(unsafestring);
    – Shmiddty
    Jan 2, 2013 at 22:13
  • 2
    @Derek That makes unsafe string url safe but not html safe.
    – James
    Jan 2, 2013 at 22:19
  • 4
    I don't think this is a duplicate: the suggested original is solving a much more specific question and requires a much more complex solution. Oct 8, 2015 at 23:58
  • 2
    best answer is to use Option class's innerHTML Ref: How to escape HTML
    – Paritosh
    Mar 24, 2021 at 6:38

5 Answers 5

78
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);

7
  • 8
    This is good for very specific symbols.
    – gdoron
    Jan 2, 2013 at 22:10
  • Quotation marks only need to be escaped for use in attributes. Jan 2, 2013 at 22:11
  • 3
    @gdoron that's the point, only 5 characters need to be escaped (ampersand, less than, greater than, single quote, double quotes).
    – Christophe
    Jan 2, 2013 at 22:13
  • Nope.. you can safely use any quotes literally if you do not need to use the escaped string within an argument... Jan 2, 2013 at 22:14
  • 2
    @gdoron example or not, it's still 5 characters to escape.
    – Christophe
    Jan 2, 2013 at 22:19
39

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

4
  • 15
    This requires jQuery which a) the question isn't tagged with and b) isn't needed.
    – j08691
    Jan 2, 2013 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 2, 2013 at 22:13
  • 4
    Agree with @j08691, it works but it's just a heavy workaround. Why the upvotes?
    – Christophe
    Jan 2, 2013 at 22:21
  • @Christophe, though it was an old comment. People upvote when something helped them.
    – gdoron
    Sep 27, 2016 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"))
3
  • +1 excellent point, although it's not clear from the question whether the OP just needs a text node or needs to combine the resulting string with others.
    – Christophe
    Jan 2, 2013 at 22:36
  • 1
    So great! An easy way around encoding :) May 26, 2017 at 22:10
  • 1
    Additionally document.createTextNode("textHere").textContent will return the string value
    – Elnoor
    Dec 23, 2022 at 0:35
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.

2
  • 1
    I love that second "magic" version with the jQuery "hack." LOVE. IT. Thanks!
    – jaressloo
    Apr 22, 2014 at 4:29
  • 1
    Does anyone know if there is there any performance difference between the two? Is the jquery one slower? Jul 14, 2016 at 18:04
-5

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

Therefore, your "magic" code is:

safestring = unsafestring.replace(/</g,'&lt;');
4
  • 6
    Wrong: you still need to escape &.
    – cdhowie
    Jan 2, 2013 at 22:08
  • I guess I'm used to allowing users to use character entities, since they're harmless. Jan 2, 2013 at 22:09
  • I don't think this is what the OP was asking. "How can a string be converted to HTML in JavaScript?" Not, "How can THIS string be converted to HTML in JavaScript?" He wants a general solution.
    – Pete
    Jan 2, 2013 at 22:10
  • 7
    I don't consider allowing input to result in invalid markup to be harmless.
    – cdhowie
    Jan 2, 2013 at 22:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.