JavaScript String localeCompare()
示例
比較 "ab" 和 "cd"
let text1 = "ab";
let text2 = "cd";
let result = text1.localeCompare(text2);
自己動手試一試 »
let text1 = "cd";
let text2 = "ab";
let result = text1.localeCompare(text2);
自己動手試一試 »
更多示例見下文。
描述
localeCompare()
方法在當前區域設定中比較兩個字串。
localeCompare()
方法返回排序順序 -1、1 或 0(分別表示之前、之後或相等)。
當前區域設定基於瀏覽器的語言設定。
語法
string.localeCompare(compareString)
引數
引數 | 描述 |
compareString | 必需。 要比較的字串。 |
返回值
型別 | 描述 |
一個數字 | 以下 3 個值之一 -1 如果字串的排序順序在 compareString 之前 0 如果兩個字串相等 1 如果字串的排序順序在 compareString 之後 |
更多示例
let text1 = "ab";
let text2 = "ab";
let result = text1.localeCompare(text2);
自己動手試一試 »
let text1 = "A";
let text2 = "a";
let result = text1.localeCompare(text2);
自己動手試一試 »
瀏覽器支援
localeCompare()
是 ECMAScript1 (ES1) 功能。
ES1 (JavaScript 1997) 在所有瀏覽器中都得到完全支援
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 是 |