zoukankan      html  css  js  c++  java
  • js 字符实体互相转换

    字符串 => 字符实体

        function stringToEntity(str,radix){
          let arr=[]
          //返回的字符实体默认10进制,也可以选择16进制
          radix=radix||0
          for(let i=0;i<str.length;i++){                               
            arr.push((!radix?'&#'+str.charCodeAt(i):'&#x'+str.charCodeAt(i).toString(16))+';')
          }
          let tmp=arr.join('')
          return tmp
        }

    字符实体 => 字符串

        function entityToString(entity){
          let entities=entity.split(';')
          entities.pop()
          let tmp=''
          for(let i=0;i<entities.length;i++){
            let num=entities[i].trim().slice(2)
            if(num[0]==='x')//10进制还是16进制
              num=parseInt(num.slice(1),16);
            else num=parseInt(num);
            tmp+=String.fromCharCode(num)
          }
          return tmp
        }

    ES6写法

    function stringToEntity(str,radix){
      let arr=str.split('')
      radix=radix||0
      let tmp=arr.map(item=>
    `&#${(radix?'x'+item.charCodeAt(0).toString(16):item.charCodeAt(0))};`).join('')
      console.log(`'${str}' 转实体为 '${tmp}'`)
      return tmp
    }
    function entityToString(entity){
      let entities=entity.split(';')
      entities.pop()
      let tmp=entities.map(item=>String.fromCharCode(
      item[2]==='x'?parseInt(item.slice(3),16):parseInt(item.slice(2)))).join('')
      console.log(`'${entity}' 转字符串为 '${tmp}'`)
      return tmp
    }

     字符转HTML实体编码

    <html>
    <head>
    <title>字符转HTML实体编码</title>
    <script>
        //HTML实体对照表: http://tool.xker.com/htmlchar.php
    function $(id) {return document.getElementById(id);}
    function htmlEncode(input)
    {
    var code = input.charCodeAt(); // 获得实体编码
    var div = $("divCode");
    /*
    * 实体编码的格式是:&#数字;
    * & 是 &
    * # 是 #
    * code 用户输入的字的实体编码
    * ; 是 ;
    *
    * 如果直接写成 "&#" + code + ";"; 的形式会被浏览器直接解析为对应的字符,从而失去了编码的作用。
    */
    div.innerHTML = "&" + "#" + code + ";"; //String.fromCharCode(code); 解码/
    }
    </script>
    </head>
    <body>
    <input type="text" onchange="htmlEncode(this.value)"/>
    <div id="divCode"></div>
    </body>
    </html>
    

      

  • 相关阅读:
    BestCoder6 1002 Goffi and Squary Partition(hdu 4982) 解题报告
    codeforces 31C Schedule 解题报告
    codeforces 462C Appleman and Toastman 解题报告
    codeforces 460C. Present 解题报告
    BestCoder3 1002 BestCoder Sequence(hdu 4908) 解题报告
    BestCoder3 1001 Task schedule(hdu 4907) 解题报告
    poj 1195 Mobile phones 解题报告
    二维树状数组 探索进行中
    codeforces 460B Little Dima and Equation 解题报告
    通过Sql语句控制SQLite数据库增删改查
  • 原文地址:https://www.cnblogs.com/7qin/p/15465264.html
Copyright © 2011-2022 走看看