Is there an easy way to convert text into HTML in JavaScript?
Question by Dejas
Possible Duplicate:
Escaping HTML strings with jQuery
JavaScript/jQuery HTML Encoding
For example, if I wanted to show the user the string x < 3
in HTML I would need to replace the <
character with <
. Is there a prebuilt function to do this in JavaScript or perhaps jQuery that converts any text string into the corresponding HTML?
Answer by bhamlin
If you want to use jQuery, you can use the text(string)
method.
$(".selector").text("x < 5");
Answer by Starx
Or, Take it simple and do this
var str1 = "x < 3";
str1.replace(/</g, '<');
Here is a function from another question
function htmlEscape(str) {
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
Or, Excellent cheat using jQuery Source
function htmlEncode(value){
return $('<div/>').text(value).html();
}
function htmlDecode(value){
return $('<div/>').html(value).text();
}