When working on a JavaScript project with AngularJS 1.6, I have a list of strings which I'd like to filter. For instance, assume my list contains árbol, cigüeña, nido and tubo.
When filtering strings in Spanish, if I filtered for "u", I'd expect both cigüeña and tubo to appear, which would be the most natural result for a Spaniard. However, this is not the case in German - u and ü are different letters and thus a German will not want to see cigüeña on the list. So I am looking for a way to make my list filtering aware of the user's locale.
I happen to have an object containing lots of diacritics, such that:
diacritics["á"] = "a";
diacritics["ü"] = "u";
// and so on...
This is what my filtering code looks like:
function matches(word, search) {
var cleanWord = removeDiacritics(word.toLowerCase());
var cleanSearch = removeDiacritics(search.toLowerCase());
return cleanWord.indexOf(cleanSearch) > -1;
}
function removeDiacritics(word) {
function match(a) {
return diacritics[a] || a;
}
return text.replace(/[^\u0000-\u007E]/g, match);
}
The above code just removes all diacritics, so I thought to make it aware of the user's locale. Thus, I changed the match() function to this:
function match(a) {
if (diacritics[a] && a.localeCompare(diacritics[a] === 0) {
return diacritics[a];
}
return a;
}
Unfortunately, this doesn't work. The localeCompare function returns the same values when comparing "u" and "ü" with the German and Spanish locales, so that was not the answer here. I've gone over the reference for the localeCompare method and tried the usage and sensitivity options, but they don't seem to help much here.
How could I tweak my code for this to work? Is there any library which can handle this properly for me?