0

There are a lot of chars converted to HTML entities in input parameters.

To use it, I need to convert the HTML entities to chars to make it readable.

How I can do it in JavaScript (interesting in be-directional convertion)?

examples:

html-code | char
-----------------
  a   |  a
3
  • How are your inputs ending up converted this way? Do you need to accept arbitrary HTML encoded characters, such as &? Are you in a browser, or in node? There is nowhere near enough information to accurately answer this. Commented Jul 17, 2020 at 2:02
  • Any solution that uses fromCharCode to decode HTML entities is wrong in the general case. Some characters happen to encode to &<ascii charcter code>; but many do not. Commented Jul 17, 2020 at 2:13
  • @meagar Yes, DOMParser would be better in case all entities need to be supported. Commented Jul 17, 2020 at 2:19

4 Answers 4

1

Just remove the prefix ("&#") and suffix (";") and use String.fromCharCode.

function entityToChar(ent){
  return String.fromCharCode(ent.slice(2,-1));
}
console.log(entityToChar("&#97;"));

If you need to support arbitrary HTML entities, you can use the DOMParser API.

function entityToChar(ent){
  return new DOMParser().parseFromString(ent, "text/html").documentElement.textContent;
}
console.log(entityToChar("&amp;"));

Sign up to request clarification or add additional context in comments.

Comments

1

You may try my code.

var div=document.createElement("div");
div.innerHTML="&#97;";
console.log(div.textContent);

Comments

0

You can use fromCharCode() for this

var a = "&#97;";

var b = String.fromCharCode(a.slice(2,-1));

console.log(b);

Comments

0

https://www.w3schools.com/jsref/jsref_fromcharcode.asp

Use fromCharCode(). But you have to use only number. From your examples '&#97' just cut '&#' out and String.fromCharCode(97).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.