Javascript 如何使用js从html实体获取实体号

Javascript 如何使用js从html实体获取实体号,javascript,html,Javascript,Html,我想使用javascript将某些实体转换为它们的实体编号。是否有一个函数可以执行此操作?我可以为一些特定的实体这样做吗 示例: 我想输出欧元实体作为其html实体号:和#8364。 这是你的电话号码 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

我想使用javascript将某些实体转换为它们的实体编号。是否有一个函数可以执行此操作?我可以为一些特定的实体这样做吗

示例:

我想输出欧元实体作为其html实体号:
和#8364

这是你的电话号码

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>

我认为您正在寻找的函数是charCodeAt,如:

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

charCodeAt函数将解决您的问题。
查看更多详细信息和示例。

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

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

const el = document.getElementById('alt-char').textContent;
其次,提取所有非标准字符(并非详尽):

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

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

const a=document.getElementById('alt-char').textContent;
常量字符=a.match(/[^\w\*!-:]/g);
const entities=chars.map(c=>(“&#”+(c.charCodeAt(0))+”);
控制台日志(实体)
我想从按钮中检索欧元字符,获取属于它的html代码,并将其输出到console.log中。因此console.log应该声明:“Euro symbol:(此处为html代码)!!!”

欧元符号:€;!!!庞德:£const chars = el.match(/[^\w\*!-: .,'"$%^&*@]/g);
const entities = chars.map(c => ('&#' + (c.charCodeAt(0)) + ';'));