escape-unescape-html-characters
Version:
This package will convert escaped html characters to unescaped characters and vice versa.
36 lines (28 loc) • 1.19 kB
JavaScript
// Contains the methods
;
const escapeHash = { '&':'&', '<':'<', '>':'>', '"':'"', "'":''' };
// This method escapes the unescaped string
// ex: <hi> gets converted to <hi>
// This prevents XSS attacks in your webpage since the tag is sanitized and won't execute in JS.
// The escaped string gets properly rendered in html
module.exports.escapeHtml = (value) => {
checkIfString(value);
return value.replace(/[&<>"']/g, replaceTag);
};
// Will perform the reverse operation of escapeHtml.
// ex: <hi> gets converted to <hi>;
module.exports.unescapeHtml = (value) => {
checkIfString(value);
// Will not be efficient to have a hash and search values from it. So directly hardcoding this. Will think of a better solution in new release.
// TODO
return value.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&');
};
function checkIfString(value) {
if (typeof value !== 'string') {
throw new TypeError(`expected string but got ${typeof value}`);
}
return;
};
function replaceTag(tag) {
return escapeHash[tag] || tag;
};