HTML特殊字符编码对照表

在设计和开发网页时,需要用到一些特殊符号,比如:©,®,℃,¥,⅜ 等等,有些上网找半天不一定能找到。HTML特殊符号编码有很多种 unicode、十六进位码(hex code),html 实体编码(entity code),还有我们熟知的html 实体(html entity) ,为了在css content属性中使用,还有对应的 css code。

你可以在HTML标签中直接插入十六进位码(hex code),html 实体编码(entity code)或者 html 实体(html entity)。在css content属性中使用则应该使用对应的 css code。需要特别注意的是:根据字体不同,部分符号显示有所不同。在项目应用中,有些时候需要将 html 和 html code进行转换,这里提供互转的两个方法:

    //JavaScript 代码
    function html_encode(str) {
      var s = '';
      if (str.length == 0) return '';
      s = str.replace(/&/g,'&');
      s = s.replace(/</g,'<');
      s = s.replace(/>/g,'>');
      s = s.replace(/ /g,'&nbsp;');
      s = s.replace(/\'/g,'&apos;');
      s = s.replace(/\"/g,'"');
      s = s.replace(/\n/g,"<br>");
        return s;
    }
    function html_decode(str) {
      var s = "";
      if (str.length==0) return '';
      s = str.replace(/&/g,'&');
      s = s.replace(/</g,'<');
      s = s.replace(/>/g,'>');
      s = s.replace(/&nbsp;/g,' ');
      s = s.replace(/&apos;/g,'\'');
      s = s.replace(/"/g,'\"');
        return s;
    }

使用DOM 的 innerHTML 和 textContent 也可以实现转换,方法是动态创建一个容器标签元素,如 DIV,将要转换的字符串设置为这个元素的 innerText,然后返回这个元素的 innerHTML,即得到经过 HTML 编码转换的字符串。

    //JavaScript 代码
    function html_encode(html) {
      return document.createElement('div').appendChild(document.createTextNode(html)).parentNode.innerHTML;
    }
    function html_decode(html) {
      var a = document.createElement('div');
      a.innerHTML = html;
      return a.textContent;
    }

这种方法有一个问题就是对于单引号’和双引号”不会进行转义处理,对于这种方法使用的时候就要非常注意了。

HTML Arrows 整理了大部分网站常用到的特殊符号,供大家参考使用:https://www.toptal.com/designers/htmlarrows/

 

由于篇幅问题,《HTML特殊字符编码对照表》分两篇写

请参照前两篇文章:

HTML特殊字符编码对照表 ——(一)

HTML特殊字符编码对照表 ——(二)

 

 

 

 

 

 

 

https://www.22vd.com/33993.html

 
posted @ 2020-10-16 15:12  格鲁特baby  阅读(1202)  评论(0编辑  收藏  举报