Skip to main content

How to Clean Up Fancy Unicode Text in User Input (JavaScript)

A small, tested way to turn styled Unicode text back into plain text before you search or compare it.

Updated 2 min readMarkdown
How to Clean Up Fancy Unicode Text in User Input (JavaScript)

Users paste ๐›๐จ๐ฅ๐, โ„ฌโ„ฏโ„ฏ๐“‡ and ๏ผจ๏ฝ…๏ฝŒ๏ฝŒ๏ฝ text into forms, and your search or duplicate check treats each one as a different string. Here is a small, tested way to turn most of it back into plain text.

The problem

Styled text is made of different Unicode characters, not fonts. So "๐‡๐ž๐ฅ๐ฅ๐จ" === "Hello" is false, and a search for "hello" will not match.

Step 1: NFKC normalization

JavaScript has String.prototype.normalize. The "NFKC" form converts many compatibility characters to their plain equivalents:

"๐‡๐ž๐ฅ๐ฅ๐จ".normalize("NFKC");  // "Hello"   (math bold)
"โ„Ž๐‘’๐‘™๐‘™๐‘œ".normalize("NFKC");  // "hello"   (math italic, with the U+210E "h")
"โ„ฌโ„ฏโ„ฏ๐“‡".normalize("NFKC");   // "Beer"    (math script)
"๏ผจ๏ฝ…๏ฝŒ๏ฝŒ๏ฝ".normalize("NFKC"); // "Hello"   (fullwidth)
"โ’ฝโ“”โ“›โ“›โ“ž".normalize("NFKC");  // "Hello"   (circled)

Step 2: what NFKC does not fix

Two common styles are left alone:

  • Strikethrough and "glitch" text use combining marks placed after each letter. NFKC keeps them.
  • Small caps such as แด€ส™แด„ come from a different block and are not mapped back.

For combining marks, decompose the string first and then remove the marks in the combining range:

const stripMarks = (s) =>
  s.normalize("NFKD").replace(/[\u0300-\u036f]/g, "");

stripMarks("s\u0336t\u0336r\u0336i\u0336k\u0336e\u0336"); // "strike"

Putting it together

export function toPlain(input) {
  return input
    .normalize("NFKD")                 // split letters from their marks
    .replace(/[\u0300-\u036f]/g, "")   // drop combining marks
    .normalize("NFKC");                // map styled letters to plain ones
}

toPlain("๐‡๐ž๐ฅ๐ฅ๐จ");          // "Hello"
toPlain("โ„ฌโ„ฏโ„ฏ๐“‡");           // "Beer"
toPlain("s\u0336t\u0336r\u0336i\u0336k\u0336e\u0336"); // "strike"

Caveats

  • Accents are removed too. "cafรฉ" becomes "cafe". Use toPlain only for search keys and comparisons, never for the text you store or show.
  • Small caps and other lookalikes stay. If you need to block lookalike characters, you need a separate list.
  • Keep the original. Store what the user typed, and use the normalized copy only to compare and index it.

Try it on real examples

To get some styled text to test with, I use the FilesSnap font generator, which converts plain text into many of these styles.

About the author

  • I run FilesSnap, a free tool that turns plain text into hundreds of fancy font styles. I write about fonts, Unicode and small web tools.

No comments yet. Be the first to comment.