Reputation: 12287
I would like input an HTML entity into the field, and when I click on submit, to have it's respective UNICODE and CSS "content" code, but I am missing some things:
http://jsfiddle.net/nadqnhbc/3/
HTML
<h1>Convert HTML entities into UNICODE & CSS</h1>
<p>Example: Enter &#128038; into the field.</p>
<input type="text" name="ampWhat">
<br>
<input id="submit" type="submit" value="Submit">
<div id="result">
<span id="result-unicode"></span>
<span id="result-css"></span>
</div>
JS
window.addEventListener("DOMContentLoaded", function () {
document.getElementById("submit").addEventListener("click", function () {
var entity = document.getElementById("ampWhat").value;
alert(entity); //Code to convert into UNICODE: U+1F426 OR CSS: "/01F426"
});
});
Upvotes: 0
Views: 1233
Reputation: 149484
To safely and accurately decode HTML entities into the original Unicode symbols, just like a browser would, use the he.decode(string)
functionality that comes with the he library:
var input = 'Enter 🐦 into the field.';
var decoded = he.decode(input);
console.log(decoded);
// → 'Enter 🐦 into the field.'
To convert the non-ASCII characters into a CSS escape sequence later, use cssesc
:
var escaped = cssesc(decoded);
console.log(escaped);
// → 'Enter \1F426 into the field.'
Here’s a jsFiddle showing this in action: https://jsfiddle.net/mathias/fbp7bftk/
Upvotes: 1