对字符串进行HTML编码和解码的JavaScript函数

对字符串进行HTML编码和解码的JS函数,记下来,方便找 :)

编码函数:

function htmlEncode(str) {
	 var s = "";
	 if (str.length == 0) return "";
	 s = str.replace(/&/g, "&");
	 s = s.replace(/</g, "&lt;");
	 s = s.replace(/>/g, "&gt;");  
	 s = s.replace(/\'/g, "&#39;");
	 s = s.replace(/\"/g, "&quot;");
	 return s;
}

解码函数:

function htmlDecode(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(/&#39;/g, "\'");   
	s = s.replace(/&quot;/g, "\""); 
	return s;   
} 
posted @ 2010-01-29 13:08  达达  阅读(2705)  评论(4编辑  收藏  举报