Reputation: 5144
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: €!!!</button>
javascript
var a = document.getElementById('alt-char').innerHTML;
console.log(a);
Upvotes: 0
Views: 1351
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: €!!! Pound: £!!!</button>
Upvotes: 1
Reputation: 810
The function charCodeAt will solve your problem. Check this out for more details and examples.
Upvotes: 1
Reputation: 779
I think the function you're looking for is charCodeAt, as in:
var str = "€";
var n = str.charCodeAt(); // n = 8364
Upvotes: 5