当秋风吹过黄昏,树叶洒落了一地,透过树干间的缝隙,有一抹夕阳,在绽放他最后的美丽……
在表单提交的数据中如果含有html代码片段,为了保证数据入库的安全性,需要对提交的内容做一下html转义,下面就来说说利用JS代码进行HTML代码的转义与反转义的方法。
JS 实现HTML转义与反转义的方法
例1:js对html进行转义
示例代码:
var html = '<p>feiniaomy.com</p><span></span>;'
//定义一个HTML转义函数
function htmlEncodeByRegExp (str){
var temp = "";
if(str.length == 0) return "";
temp = str.replace(/&/g,"&");
temp = temp.replace(/</g,"<");
temp = temp.replace(/>/g,">");
temp = temp.replace(/\s/g," ");
temp = temp.replace(/\'/g,"'");
temp = temp.replace(/\"/g,""");
return temp;
}
console.log(htmlEncodeByRegExp(html));
// <p>feiniaomy.com</p><span></span>;例2:js对html代码进行反转义
示例代码:
var html = '<p>feiniaomy.com</p><span></span>;'
//JS 对html进行反转义
function htmlDecodeByRegExp (str){
var temp = "";
if(str.length == 0) return "";
temp = str.replace(/&/g,"&");
temp = temp.replace(/</g,"<");
temp = temp.replace(/>/g,">");
temp = temp.replace(/ /g," ");
temp = temp.replace(/'/g,"\'");
temp = temp.replace(/"/g,"\"");
return temp;
}
console.log(htmlDecodeByRegExp(html));
//<p>feiniaomy.com</p><span></span>;例3:js利用正规对html进行反转义
示例代码:
var html = '<p>feiniaomy.com</p><span></span>;'
function escape2Html (str) {
var arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
return str.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
}
console.log(escape2Html(html));
//<p>feiniaomy.com</p><span></span>;例4:js利用正规对html进行转义
示例代码:
var html = '<p>feiniaomy.com</p><span></span>';
function html2Escape(sHtml) {
return sHtml.replace(/[<>&"]/g,function(c){return {'<':'<','>':'>','&':'&','"':'"'}[c];});
}
console.log(html2Escape(html));
//<p>feiniaomy.com</p><span></span> 以上就是如何利用JS代码如何实现HTML转义与反转义的方法。再也不见,是我们送给彼此最好的礼物。更多关于如何利用JS代码如何实现HTML转义与反转义的方法请关注haodaima.com其它相关文章!




