I am using an AJAX-based lookup for names that a user searches in a text box.
I am making the assumption that all names in the database will be transliterated to European alphabets (i.e. no Cyrillic, Japanese, Chinese). However, the names will still contain accented characters, such as ç, ê and even č and ć.
A simple search like "Micic" will not match "Mičić" though - and the user expectation is that it will.
The AJAX lookup uses regular expressions to determine a match. I have modified the regular expression comparison using this function in an attempt to match more accented characters. However, it's a little clumsy since it doesn't take into account all characters.
function makeComp (input) { input = input.toLowerCase (); var output = ''; for (var i = 0; i < input.length; i ++) { if (input.charAt (i) == 'a') output = output + '[aàáâãäåæ]' else if (input.charAt (i) == 'c') output = output + '[cç]'; else if (input.charAt (i) == 'e') output = output + '[eèéêëæ]'; else if (input.charAt (i) == 'i') output = output + '[iìíîï]'; else if (input.charAt (i) == 'n') output = output + '[nñ]'; else if (input.charAt (i) == 'o') output = output + '[oòóôõöø]'; else if (input.charAt (i) == 's') output = output + '[sß]'; else if (input.charAt (i) == 'u') output = output + '[uùúûü]'; else if (input.charAt (i) == 'y') output = output + '[yÿ]' else output = output + input.charAt (i); } return output; }
Apart from a substitution function like this, is there a better way? Perhaps to "deaccent" the string being compared?
replace(/[^a-z0-9]/gi,'') . However a more intuitive solution (at least for the user) would be to replace accented characters with their "plain" equivalent, e.g. turn á , á into a , and ç into c , etc.
string = string. replaceAll("[^\\p{ASCII}]", "");
There is a way to “"deaccent" the string being compared” without the use of a substitution function that lists all the accents you want to remove…
Here is the easiest solution I can think about to remove accents (and other diacritics) from a string.
See it in action:
var string = "Ça été Mičić. ÀÉÏÓÛ"; console.log(string); var string_norm = string.normalize('NFD').replace(/[\u0300-\u036f]/g, ""); console.log(string_norm);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With