Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Javascript UTF-8 to ASCII (like Iconv('UTF-8', 'ASCII//TRANSLIT', $string) in PHP)

I'm wondering how it's possible to 'translate' characters in UTF-8 to the closest ASCII equivalent using Javascript, just like Iconv doest in PHP.

Example:

ü becomes u
ó becomes o

I'd rather not use a replace, because a) it requires a complete set of characters, which is a lot of work and b) i'd would be hard to get a complete set of characters, and i'll never be certain if i'm missing one or two.

like image 543
Simon Avatar asked Nov 09 '12 14:11

Simon


2 Answers

There is now a port of iconv to JS: https://www.npmjs.com/package/iconv

var iconv = new Iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE');
iconv.convert('ça va が'); // "ca va "
like image 115
Madarco Avatar answered Sep 23 '22 03:09

Madarco


The easiest way I've found:

var str = "üó";
var combining = /[\u0300-\u036F]/g; 

console.log(str.normalize('NFKD').replace(combining, ''));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize

like image 29
Rez Avatar answered Sep 24 '22 03:09

Rez