将用户输入内容中的尖括号、引号等进行转义

此方法用来将用户输入内容中的尖括号、引号等进行转义

function html_encode(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, "&nbsp;"); 
s = s.replace(/\'/g, "&#39;"); 
s = s.replace(/\"/g, "&quot;"); 
s = s.replace(/\n/g, "<br>"); 
return s; 
}

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

方法二

function htmlEncode(str) {
var div = document.createElement("div");
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
function htmlDecode(str) {
var div = document.createElement("div");
div.innerHTML = str;
return div.innerHTML;
}

链接:http://www.oschina.net/code/snippet_12_3293

 

 

posted @ 2014-01-06 19:36  梅梅哇  阅读(11655)  评论(2编辑  收藏  举报