Search code examples
javascripthtml

How to encode a string in JavaScript for displaying in HTML?


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.


Solution

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