In JavaScript, how to escape HTML characters?
The following JavaScript code is used to convert special characters into HTML entities:
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escapeHtml (string) {
return String(string).replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
});
}
Here is the result:
var before="\" \' & < > =";
var after = escapeHtml(before);
// Affiche "Before : " ' & < > ="
console.log ("Before : " + before);
// Affiche : "After : " ' & < > ="
console.log ("After : " + after);
Try online on JSFiddle.
Source : Escaping HTML strings with jQuery
The following JavaScript code is used to convert special characters into HTML entities:
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escapeHtml (string) {
return String(string).replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
});
}
Here is the result:
var before="\" \' & < > =";
var after = escapeHtml(before);
// Affiche "Before : " ' & < > ="
console.log ("Before : " + before);
// Affiche : "After : " ' & < > ="
console.log ("After : " + after);
Try online on JSFiddle.
Source : Escaping HTML strings with jQuery
The following JavaScript code is used to convert special characters into HTML entities:
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escapeHtml (string) {
return String(string).replace(/[&<>"'`=\/]/g, function (s) {
return entityMap[s];
});
}
Here is the result:
var before="\" \' & < > =";
var after = escapeHtml(before);
// Affiche "Before : " ' & < > ="
console.log ("Before : " + before);
// Affiche : "After : " ' & < > ="
console.log ("After : " + after);
Try online on JSFiddle.
Source : Escaping HTML strings with jQuery
# | ID | Query | URL | Count |
---|