Skip to content

Instantly share code, notes, and snippets.

@monjer
Last active December 26, 2015 18:19
Show Gist options
  • Select an option

  • Save monjer/7193551 to your computer and use it in GitHub Desktop.

Select an option

Save monjer/7193551 to your computer and use it in GitHub Desktop.
普通版的html前台字符转义与反转义
(function(opt_ns , opt_win){
/**
* @date 2013.10.28
* reference:
* http://zh.wikipedia.org/wiki/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F
* http://www.w3school.com.cn/js/jsref_replace.asp
*/
var escapeMapping = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#x27;'
};
var unescapeMapping = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#x27;': "'"
};
var html = {
/**
* html字符转义
* @param htmlString {String}
* @returns {String} 转义后的普通文本
*/
escape:function(htmlString){
if(htmlString){
return htmlString.toString().replace(/[&<>\"']/g,function(match){
return escapeMapping[match];
});
}else{
return "";
}
},
/**
* 普通文本转义为html文本
* @param plainText {String}
* @returns {String} 反转义后的html文本
*/
unescape:function(plainText){
if(plainText){
return plainText.toString().replace(/&amp;|&lt;|&gt;|&quot;|&#x27;/g,function(match){
return unescapeMapping[match];
});
}else{
return "";
}
}
};
opt_win = opt_win || top ;
opt_ns = opt_ns || opt_win ;
opt_ns.html = html ;
})();
@monjer

monjer commented Oct 28, 2013

Copy link
Copy Markdown
Author
// 或使用以下简单的处理
function HTMLEscape ( htmlString )
{
   var converter = document.createElement("div");
   converter.innerText = htmlString;
   var output = converter.innerHTML;
   converter = null;
   return output;
}
function HTMLUnescape ( plainText )
{
   var converter = document.createElement("div");
   converter.innerHTML = plainText;
   var output = converter.innerText;
   converter = null;
   return output;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment