Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
How can i convert every special character and emoji into its html entity using javascript?

My current code converts characters into entities as expected. But if I convert emoji, then it generates something like �� for 🤩 which doesn't render as expected.

String.prototype.toHtmlEntities = function() {
  return this.replace(/./gm, function(s) {
    // return "&#" + s.charCodeAt(0) + ";";
    return (s.match(/[a-z0-9\s]+/i)) ? s : "&#" + s.charCodeAt(0) + ";";
  });
};
console.log("🤩".toHtmlEntities())

document.write("🤩".toHtmlEntities())

about 4 years ago Ā· Juan Pablo Isaza
1 answers
Answer question

0

You're iterating over the code units of your string. Instead, you want to iterate over the code points. Most emojis consist of one code point, which is encoded by two code units called surrogate pairs - one high and one low one. Surrogate pairs when displayed standalone don't represent a valid symbol, which ends up with ļæ½ being rendered. If you use the u (unicode) flag on your regular expression, your . will then match based on the code points, allowing you to iterate over each code point (rather than code unit). You can then access the code point value using codePointAt(0), which you can then encode into a HTML entity:

String.prototype.toHtmlEntities = function() {
  return this.replace(/./ugm, s => s.match(/[a-z0-9\s]+/i) ? s : "&#" + s.codePointAt(0) + ";");
};
console.log("a".toHtmlEntities());
document.write("a".toHtmlEntities());

console.log("&".toHtmlEntities());
document.write("&".toHtmlEntities());

console.log("šŸ˜".toHtmlEntities()); // surrogate pair test
document.write("šŸ˜".toHtmlEntities());

console.log("šŸ‘Øā€šŸ‘©ā€šŸ‘§ā€šŸ‘¦".toHtmlEntities()); // ZWJ test
document.write("šŸ‘Øā€šŸ‘©ā€šŸ‘§ā€šŸ‘¦".toHtmlEntities());

console.log("ā¤ļø".toHtmlEntities()); // variation selector test
document.write("ā¤ļø".toHtmlEntities()); // variation selector test

console.log("ñ".toHtmlEntities()); // decomposed character test (length of 2)
document.write("ñ".toHtmlEntities()); // decomposed character test (length of 2)

console.log("Ʊ".toHtmlEntities()); // composed character (length of 1)
document.write("Ʊ".toHtmlEntities()); // composed character (length of 1)

about 4 years ago Ā· Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
Ā© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!