【问题标题】:How to get the entity number from an html entity with js如何使用js从html实体中获取实体号
【发布时间】:2017-09-17 01:18:29
【问题描述】:

我想使用 javascript 将某些实体转换为其实体编号。有这样做的功能吗?我可以为某些特定实体做这件事吗?

示例:

我想在控制台中输出 € 实体作为其 html 实体编号:€

这里是JSFiddle

html

<div>I want to retreive the euro character from the button, get the html code that belongs to it and output it in the console.log. So the console.log should state: "Euro-symbol: (html code here)!!!"</div>
<button id="alt-char">Euro-symbol: &#8364;!!!</button>

javascript

var a = document.getElementById('alt-char').innerHTML;
console.log(a);

【问题讨论】:

  • 您能对这个问题多加一点解释吗?目前有点难以理解你想要什么。
  • @evolutionxbox 我在问题中添加了一个示例。希望它可以清除一点。
  • 我设法使用 charCode 和来自 Ines Tlili 的链接的一些灵感来整理一个解决方案:jsfiddle.net/w5ocjwv8/2 谢谢大家的帮助 :)。

标签: javascript html


【解决方案1】:

与其他答案一样,建议使用charCodeAt 检索字符的值。

首先,获取所需元素的textContent:

const el = document.getElementById('alt-char').textContent;

其次,提取所有非标准字符(不详尽):

const chars = el.match(/[^\w\*!-: .,'"$%^&*@]/g);

最后,将字符转换为 HTML 实体:

const entities = chars.map(c => ('&#' + (c.charCodeAt(0)) + ';'));

例子:

const a = document.getElementById('alt-char').textContent;
const chars = a.match(/[^\w\*!-: ]/g);
const entities = chars.map(c => ('&#' + (c.charCodeAt(0)) + ';'));
console.log(entities);
<div>I want to retreive the euro character from the button, get the html code that belongs to it and output it in the console.log. So the console.log should state: "Euro-symbol: (html code here)!!!" </div>
<button id="alt-char">Euro-symbol: &#8364;!!! Pound: &#163;!!!</button>

【讨论】:

    【解决方案2】:

    charCodeAt 函数将解决您的问题。 查看this 了解更多详情和示例。

    【讨论】:

      【解决方案3】:

      我认为您要查找的函数是 charCodeAt,如:

      var str = "€";
      var n = str.charCodeAt(); // n = 8364
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-16
        • 1970-01-01
        • 1970-01-01
        • 2020-07-03
        相关资源
        最近更新 更多