0

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);
Rob Monhemius
  • 4,822
  • 2
  • 17
  • 49
  • Could you add a bit more explanation to the question? At the moment it's a little hard to understand what you want. – evolutionxbox Apr 20 '17 at 12:06
  • @evolutionxbox I added an example to the question. hope it clears it up a bit. – Rob Monhemius Apr 20 '17 at 12:11
  • look at this link http://stackoverflow.com/questions/6639770/how-do-i-get-the-unicode-hex-representation-of-a-symbol-out-of-the-html-using-ja – Yu Jiaao Apr 20 '17 at 12:58
  • I managed to fiddle together a solution using charCode and some inspiration from the link from Ines Tlili : https://jsfiddle.net/w5ocjwv8/2/ Thanks everyone for the help :). – Rob Monhemius Apr 20 '17 at 15:10

3 Answers3

5

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

var str = "€";
var n = str.charCodeAt(); // n = 8364
piisexactly3
  • 779
  • 7
  • 16
1

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

Ines Tlili
  • 790
  • 6
  • 21
1

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>
evolutionxbox
  • 3,932
  • 6
  • 34
  • 51