Rob Monhemius
Rob Monhemius

Reputation: 5144

How to get the entity number from an html entity with js

I want to convert certain entities to their entity numbers, using javascript. Is there a function to do this? Could I do it for some specific entities?

Example:

I want to output the € entity as its html-entity number: € in the console.

Here is the 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);

Upvotes: 0

Views: 1351

Answers (3)

evolutionxbox
evolutionxbox

Reputation: 4122

Like the other answers, using charCodeAt to retrieve the value of the character is recommended.

Firstly, get the textContent of the desired element:

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

Secondly, extract all non-standard characters (not exhaustive):

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

Lastly, convert the characters into HTML entities:

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

Example:

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>

Upvotes: 1

Ines Tlili
Ines Tlili

Reputation: 810

The function charCodeAt will solve your problem. Check this out for more details and examples.

Upvotes: 1

piisexactly3
piisexactly3

Reputation: 779

I think the function you're looking for is charCodeAt, as in:

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

Upvotes: 5

Related Questions