escape html code javascript code example
Example 1: javascript escape html
function escapeHtml(str) {
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}
Example 2: jquery escape html string
//escaping HTML with jquery
var dangerousHTML = "<script>alert('Badabing Baby!');</script>";
$("#myElementID").text(dangerousHTML); //.text() function will escape and display text
//Alternatively, here is plain Javascript escape function
function escapeHtml(str) {
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}