How to convert unicode to ascii in javascript or php?

Member

by kadin , in category: PHP General , 2 months ago

How to convert unicode to ascii in javascript or php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 2 months ago

@kadin 

JavaScript:


To convert Unicode to ASCII in JavaScript, you can use the String.prototype.normalize() method followed by replace() method to remove or replace any non-ASCII characters.


Example:

1
2
3
const unicodeString = "Héllø Wörld";
const asciiString = unicodeString.normalize('NFD').replace(/[̀-ͯ]/g, '');
console.log(asciiString); // Output: Hello World


PHP:


To convert Unicode to ASCII in PHP, you can use the Transliterator::transliterate() function from the Transliterator class.


Example:

1
2
3
4
$unicodeString = "Héllø Wörld";
$transliterator = Transliterator::create('NFD; [:Nonspacing Mark:] Remove; NFC');
$asciiString = $transliterator->transliterate($unicodeString);
echo $asciiString; // Output: Hello World


Make sure to have the intl extension enabled in your PHP configuration to use the Transliterator class.