Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode a string in JavaScript for displaying in HTML? [duplicate]

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.

like image 788
James Avatar asked Jan 02 '13 22:01

James


People also ask

How do I decode a string in HTML?

HtmlDecode(String, TextWriter) Converts a string that has been HTML-encoded into a decoded string, and sends the decoded string to a TextWriter output stream.

How are strings encoded in JavaScript?

In order to encode/decode a string in JavaScript, We are using built-in functions provided by JavaScript. btoa(): This method encodes a string in base-64 and uses the “A-Z”, “a-z”, “0-9”, “+”, “/” and “=” characters to encode the provided string.


1 Answers

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

like image 160
j08691 Avatar answered Sep 28 '22 16:09

j08691