Sometimes, we want to convert HTML character entities back to regular text using JavaScript
In Hit article, we’ll look at how to convert HTML character entities back to regular text using JavaScript.
How to convert HTML character entities back to regular text using JavaScript?
To convert HTML character entities back to regular text using JavaScript, we can put the HTML character entities into an element.
Then we can get the regular text from the element.
For instance, we write:
const decodeEntities = (s) => {
const el = document.createElement('p');
el.innerHTML = s;
const str = el.textContent
return str;
}
console.log(decodeEntities('<'))
to define the decodeEntities that takes the s string.
In it, we create a p element with createElement.
Then we set el.innerHTML to s.
And then we return el.textContent which has the regular text converted from s.
As a result, the console log logs '<'.
Conclusion
To convert HTML character entities back to regular text using JavaScript, we can put the HTML character entities into an element.
Then we can get the regular text from the element.