【问题标题】:how to decode hex code of html entities to text in javascript?如何将html实体的十六进制代码解码为javascript中的文本?
【发布时间】:2014-10-25 19:24:10
【问题描述】:

我在将字符串字符的十六进制值转换为正常测试值时遇到困难 例如,' 的十六进制值是',即撇号。

可以在此链接上找到其他十六进制字符值:http://character-code.com/

有人可以告诉我是否有 javascript 方法可以做到这一点,或者我应该为此目的使用一些外部 javascript 库插件吗?

我已经尝试过使用URIencodeURIencodecomponent 但没有成功

【问题讨论】:

    标签: javascript string text hex decode


    【解决方案1】:

    您可以使用主机提供的解析器将实体插入元素中,然后取回 textContent(或支持的 innerText):

    var el = document.createElement('span');
    el.innerHTML = ''';
    
    console.log('' is a ' +  (el.textContent || el.innerText));  // ' is a '
    

    当然,这不适用于浏览器不支持的实体。

    编辑

    把上面的变成一个函数:

    var entityToText = (function() {
    
      // Create a single span to parse the entity
      var span = document.createElement('span');
    
      // Choose textContent or innerText depending on support
      var theText = typeof span.textContent == 'string'? 'textContent' : 'innerText';
    
      // Return the actual function
      return function(entity) {
        span.innerHTML = entity;
        return span[theText];
      }
    }());
    

    【讨论】:

      【解决方案2】:

      您可以使用String.fromCharCode - 但您首先需要将十六进制值(以 16 为底)转换为整数(以 10 为底)。以下是你的做法:

          var encoded = "'";
          var REG_HEX = /&#x([a-fA-F0-9]+);/g;
      
          var decoded = encoded.replace(REG_HEX, function(match, group1){
              var num = parseInt(group1, 16); //=> 39
              return String.fromCharCode(num); //=> '
          });
      
          console.log(decoded); //=> "'"
      

      要将十进制转换回十六进制,您可以这样做:

          decoded.toString(16); //=> 27
      

      【讨论】:

      • +1 网络上唯一基于代码的答案。很好谢谢。我使用您的方法编写了一个函数,该函数在下面的答案中。
      【解决方案3】:

      只需使用此源自 Ryan Wheale 解决方案的函数即可将任何数字十六进制 Html 字符串转换为友好字符串:

      function hexHtmlToString(str) {
          var REG_HEX = /&#x([a-fA-F0-9]+);/g;
          return str.replace(REG_HEX, function(match, grp){
              var num = parseInt(grp, 16);
              return String.fromCharCode(num);
          });
      }
      

      用法:

      var str = 'سلام';
      console.log(hexHtmlToString(str)); //results: سلام
      

      【讨论】:

        猜你喜欢
        • 2011-11-20
        • 2011-03-29
        • 2020-06-15
        • 1970-01-01
        • 2012-10-13
        • 1970-01-01
        • 1970-01-01
        • 2018-10-13
        • 1970-01-01
        相关资源
        最近更新 更多