How to convert unicode to ascii in javascript or php?

by edmond_brakus , in category: PHP General , 9 months ago

How to convert unicode to ascii in javascript or php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , 9 months ago

@edmond_brakus 

In JavaScript, you can use the String.prototype.normalize() method to convert Unicode characters to their closest ASCII equivalents. Here's an example using ES6:

1
2
3
const unicodeString = "München";
const asciiString = unicodeString.normalize('NFD').replace(/[̀-ͯ]/g, '');
console.log(asciiString); // Output: "Munchen"


Explanation:

  1. The normalize() method normalizes the string into Unicode Normalization Form D (NFD). This separates the accented characters into basic characters and combining diacritical marks.
  2. The replace() method removes any remaining combining diacritical marks from the string.
  3. The resulting string will have the closest ASCII equivalents for the original Unicode characters.


In PHP, you can use the transliterator_transliterate() function to convert Unicode characters to ASCII equivalents. Here's an example:

1
2
3
$unicodeString = "München";
$asciiString = transliterator_transliterate('Any-Latin; Latin-ASCII;', $unicodeString);
echo $asciiString; // Output: "Munchen"


Explanation:

  1. The transliterator_transliterate() function performs transliteration using the specified transliteration rule (in this case, 'Any-Latin; Latin-ASCII;').
  2. The resulting string will have the closest ASCII equivalents for the original Unicode characters.


Please note that some characters may not have direct ASCII equivalents, so the conversion may not always be perfect.