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 |
|---|---|---|---|---|
| 0 | 13627 | alphons | https://en.ans.wiki/6887/in-javascript-how-to-escape-html-characters | 1 |
| 1 | 12635 | en | https://en.ans.wiki/6887/in-javascript-how-to-escape-html-characters | 7 |