使用 js 實現(xiàn)不區(qū)分大小寫和重音的字符串比較
比較和排序 Javascript 字符串是相當(dāng)常見的。通常,在大多數(shù)情況下,使用 String.prototype.localeCompare() 方法就足以對字符串?dāng)?shù)組進行排序。然而,處理口音和大小寫可能會變得棘手,并導(dǎo)致意想不到的結(jié)果。這是 Intl.Collator 發(fā)揮作用的地方,一個用于語言敏感字符串比較的對象。使用 Intl.Collator.prototype.compare(),您可以不考慮大小寫或重音對字符串進行排序,它甚至可以接受語言環(huán)境參數(shù)。
Javascript
const arr = ['?', 'a', 'b', 'A', 'B', '?'];const localeCompare = (a, b) => a.localeCompare(b);const collator = new Intl.Collator();const deCollator = new Intl.Collator('de');const svCollator = new Intl.Collator('sv');
示例:
arr.sort(localeCompare); // ['a', 'A', '?', '?', 'b', 'B']arr.sort(collator.compare); // ['a', 'A', '?', '?', 'b', 'B']arr.sort(deCollator.compare); // ['a', 'A', '?', '?', 'b', 'B']arr.sort(svCollator.compare); // ['a', 'A', 'b', 'B', '?', '?']
更多內(nèi)容請訪問我的網(wǎng)站:https://www.icoderoad.com