如何在JavaScript中執行不區分大小寫的字符串比較? html
我寫了一個擴展名。 很是瑣碎 正則表達式
if (typeof String.prototype.isEqual!= 'function') { String.prototype.isEqual = function (str){ return this.toUpperCase()==str.toUpperCase(); }; }
藉助正則表達式,咱們也能夠實現。 瀏覽器
(/keyword/i).test(source)
/i
用於忽略大小寫。 若是沒有必要,咱們能夠忽略並測試不區分大小寫的匹配項,例如 app
(/keyword/).test(source)
請記住,大小寫是特定於語言環境的操做。 根據狀況,您可能須要考慮這一點。 例如,若是您要比較兩我的的姓名,則可能要考慮語言環境,但若是要比較計算機生成的值(例如UUID),則可能不須要。 這就是爲何我在utils庫中使用如下函數的緣由(請注意,出於性能緣由不包括類型檢查)。 ide
function compareStrings (string1, string2, ignoreCase, useLocale) { if (ignoreCase) { if (useLocale) { string1 = string1.toLocaleLowerCase(); string2 = string2.toLocaleLowerCase(); } else { string1 = string1.toLowerCase(); string2 = string2.toLowerCase(); } } return string1 === string2; }
最簡單的方法(若是您不擔憂特殊的Unicode字符)是調用toUpperCase
: 函數
var areEqual = string1.toUpperCase() === string2.toUpperCase();
編輯 :這個答案最初是9年前添加的。 今天,您應該將localeCompare
與sensitivity: 'accent'
選項結合使用: 性能
function ciEquals(a, b) { return typeof a === 'string' && typeof b === 'string' ? a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0 : a === b; } console.log("'a' = 'a'?", ciEquals('a', 'a')); console.log("'AaA' = 'aAa'?", ciEquals('AaA', 'aAa')); console.log("'a' = 'á'?", ciEquals('a', 'á')); console.log("'a' = 'b'?", ciEquals('a', 'b'));
{ sensitivity: 'accent' }
告訴localeCompare()
將相同基本字母的兩個變體視爲相同, 除非它們的重音不一樣(如第三個示例中所示)。 測試
另外,您可使用{ sensitivity: 'base' }
,只要兩個字符的基本字符相同就將其視爲等效(所以A
將被視爲等同於á
)。 this
請注意 ,在IE10或更低版本或某些移動瀏覽器中,不支持localeCompare
的第三個參數(請參見上面連接的頁面上的兼容性圖表),所以,若是須要支持這些瀏覽器,則須要某種後備: spa
function ciEqualsInner(a, b) { return a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0; } function ciEquals(a, b) { if (typeof a !== 'string' || typeof b !== 'string') { return a === b; } // v--- feature detection return ciEqualsInner('A', 'a') ? ciEqualsInner(a, b) : /* fallback approach here */; }
原始答案
在JavaScript中進行不區分大小寫的比較的最佳方法是使用帶有i
標誌的RegExp match()
方法。
當兩個被比較的字符串都是變量(不是常量)時,這會稍微複雜一點,由於您須要從字符串生成RegExp,可是若是字符串具備特殊的regex,則將字符串傳遞給RegExp構造函數可能會致使不正確的匹配或失敗的匹配裏面的字符。
若是您關心國際化,請不要使用toLowerCase()
或toUpperCase()
由於它不能在全部語言中提供準確的不區分大小寫的比較。