programming-examples/js/String/Escapes special characters for use in HTML.js

19 lines
503 B
JavaScript
Raw Normal View History

2019-11-15 12:59:38 +01:00
function escape_html(str) {
if ((str===null) || (str===''))
return false;
else
str = str.toString();
var map = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#039;'
};
return str.replace(/[&<>"']/g, function(m) { return map[m]; });
}
console.log(escape_html('PHP & MySQL'));
console.log(escape_html('3 > 2'));