简体   繁体   中英

How convert html code to char in javascript?

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

You may try my code.

 var div=document.createElement("div"); div.innerHTML="a"; console.log(div.textContent);

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

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

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("&"));

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) .

You can use fromCharCode() for this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM