Skip to content

Instantly share code, notes, and snippets.

@ziluo
Created October 18, 2012 03:11
Show Gist options
  • Save ziluo/3909663 to your computer and use it in GitHub Desktop.
Save ziluo/3909663 to your computer and use it in GitHub Desktop.
html_encode and html_decode
/**
* 将含有html等特殊字符转义
* 使用实例:$.html_encode("<p>li</p>")
*/
(function($){
$.extend({"html_encode":function(str) {
var s = "";
if (str==null || typeof(str)=='undefined' || str.length == 0) return "";
s = str.replace(/&/g, "&amp;");
s = s.replace(/</g, "&lt;");
s = s.replace(/>/g, "&gt;");
s = s.replace(/ /g, "&nbsp;");
s = s.replace(/\'/g, "'");
s = s.replace(/\"/g, "&quot;");
s = s.replace(/\n/g, "<br>");
return s;
},"html_decode":function(str){
var s = "";
if (str.length == 0) return "";
s = str.replace(/&amp;/g, "&");
s = s.replace(/&lt;/g, "<");
s = s.replace(/&gt;/g, ">");
s = s.replace(/&nbsp;/g, " ");
s = s.replace(/'/g, "\'");
s = s.replace(/&quot;/g, "\"");
s = s.replace(/<br>/g, "\n");
return s;
}});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment