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);
4
  • Could you add a bit more explanation to the question? At the moment it's a little hard to understand what you want. Commented Apr 20, 2017 at 12:06
  • @evolutionxbox I added an example to the question. hope it clears it up a bit. Commented Apr 20, 2017 at 12:11
  • look at this link stackoverflow.com/questions/6639770/… Commented Apr 20, 2017 at 12:58
  • I managed to fiddle together a solution using charCode and some inspiration from the link from Ines Tlili : jsfiddle.net/w5ocjwv8/2 Thanks everyone for the help :). Commented Apr 20, 2017 at 15:10

3 Answers 3

5

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

var str = "€";
var n = str.charCodeAt(); // n = 8364
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.