1

In a React app, I need to send to a backend a search term with Unicode Decimal characters.

If the user enters ä, I need to convert it to ä

If the user enters KivisiltaöøäÅåÄ I need to convert it to KivisiltaöøäÅåÄ

How to do it automatically for all most common latin letters and Latin-1 supplement?

I found this very useful article to parse it: Replace unicode characters with characters (Javascript) But I need the contrary, to encode it.

Raphael Pinel
  • 2,352
  • 24
  • 26

1 Answers1

2

If you want to encode every non-ASCII character, use this:

function encode(str) {
  let out = "";
  for (const char of str) {
    const code = char.codePointAt(0);
    if (code >= 0x80)
      out += `&#${code};`;
    else
      out += char;
  }
  return out;
}

console.log(encode("KivisiltaöøäÅåÄ"));
D. Pardal
  • 6,173
  • 1
  • 17
  • 37