Skip to content

Instantly share code, notes, and snippets.

@guoshuai93
Created January 21, 2021 02:48
Show Gist options
  • Save guoshuai93/612156f851f2302b930d810c42ad6af2 to your computer and use it in GitHub Desktop.
Save guoshuai93/612156f851f2302b930d810c42ad6af2 to your computer and use it in GitHub Desktop.
HTML转义和反转义的方法
/**
* 转义HTML标签的方法
* @param {String} str 需要转义的HTML字符串
* @return {String} 转义后的字符串
*/
var funEncodeHTML = function (str) {
if (typeof str == 'string') {
return str.replace(/<|&|>/g, function (matches) {
return ({
'<': '&lt;',
'>': '&gt;',
'&': '&amp;'
})[matches];
});
}
return '';
};
/**
* 反转义HTML标签的方法
* @param {String} str 需要反转义的字符串
* @return {String} 反转义后的字符串
*/
var funDecodeHTML = function (str) {
if (typeof str == 'string') {
return str.replace(/&lt;|&gt;|&amp;/g, function (matches) {
return ({
'&lt;': '<',
'&gt;': '>',
'&amp;': '&'
})[matches];
});
}
return '';
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment