HTML的Encode(转码)和Decode(解码) 您所在的位置:网站首页 html在线编码转换 HTML的Encode(转码)和Decode(解码)

HTML的Encode(转码)和Decode(解码)

#HTML的Encode(转码)和Decode(解码)| 来源: 网络整理| 查看: 265

 HTML的Encode(转码)和解码(Decode)在平时的开发中也是经常要处理的,在这里总结了使用javascript处理HTML的Encode(转码)和解码(Decode)的常用方式

1.用浏览器内部转换器实现html转码

  首先动态创建一个容器标签元素,如DIV,然后将要转换的字符串设置为这个元素的innerText(ie支持)或者textContent(火狐,google支持),最后返回这个元素的innerHTML,即得到经过HTML编码转换的字符串了。

2.用浏览器内部转换器实现html解码

  首先动态创建一个容器标签元素,如DIV,然后将要转换的字符串设置为这个元素的innerHTML(ie,火狐,google都支持),最后返回这个元素的innerText(ie支持)或者textContent(火狐,google支持),即得到经过HTML解码的字符串了。

3.具体实现代码

var HtmlUtil = { /*1.用浏览器内部转换器实现html转码*/ htmlEncode:function (html){ //1.首先动态创建一个容器标签元素,如DIV var temp = document.createElement ("div"); //2.然后将要转换的字符串设置为这个元素的innerText(ie支持)或者textContent(火狐,google支持) (temp.textContent != undefined ) ? (temp.textContent = html) : (temp.innerText = html); //3.最后返回这个元素的innerHTML,即得到经过HTML编码转换的字符串了 var output = temp.innerHTML; temp = null; return output; }, /*2.用浏览器内部转换器实现html解码*/ htmlDecode:function (text){ //1.首先动态创建一个容器标签元素,如DIV var temp = document.createElement("div"); //2.然后将要转换的字符串设置为这个元素的innerHTML(ie,火狐,google都支持) temp.innerHTML = text; //3.最后返回这个元素的innerText(ie支持)或者textContent(火狐,google支持),即得到经过HTML解码的字符串了。 var output = temp.innerText || temp.textContent; temp = null; return output; } };

测试

var html = "aaaaaa

bbbb

"; var encodeHtml = HtmlUtil.htmlEncode(html); alert("encodeHtml:" + encodeHtml); var decodeHtml = HtmlUtil.htmlDecode(encodeHtml); alert("decodeHtml:" + decodeHtml);

运行结果:



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有