javascript中涉及到漢字的比較


在使用js中的"=="進行字符串的比較時,發現在英文情況下是ok的,但在中文比較時則不行了。

在網上搜索,提供了一個解決方法,使用

stringObject.localeCompare(target)

來解決中文比較問題。

string_a.localeCompare(string_b);

/* Returns:

 0:  exact match

-1:  string_a < string_b

 1:  string_b > string_b

 */

這個方法的用法是:確定兩個字符串在當前區域設置中是否相等。

微軟資料如下:

http://msdn.microsoft.com/zh-cn/library/ie/62b7ahzy(v=vs.94).aspx

localeCompare 方法 (String) (JavaScript)

 

確定兩個字符串在當前區域設置中是否相等。

 
 
stringVar.localeCompare(stringExp[, locales][, options]) 
參數
 
stringVar

必需。 要比較的第一個字符串。

stringExp

必需。 要比較的第二個字符串。

locales

可選。 包含一種或多種語言或區域設置標記的區域設置字符串數組。 如果包含多個區域設置字符串,請以降序優先級對它們進行排列,確保首個條目為首選區域位置。 如果省略此參數,則使用 JavaScript 運行時的默認區域設置。 此參數必須符合 BCP 47 標准;請參見 Intl.Collator 對象了解詳細信息。

options

可選。 包含指定比較選項的一個或多個特性的對象。請參見 Intl.Collator 對象了解詳細信息。

備注
 

對於比較字符串,可以指定 String 對象或字符串文本。

從 Internet Explorer 11 開始,localeCompare 在內部使用 Intl.Collator 對象進行比較,添加對 locales 和options 參數的支持。 有關這些參數的詳細信息,請參見 Intl.Collator 和 Intl.Collator.compare

重要事項

locales 和 options 參數在所有的文檔模型和瀏覽器版本中均不支持。 有關詳細信息,請參見“要求”部分。

localeCompare 方法對 stringVar 和 stringExp 執行區分區域設置的字符串比較,並返回以下結果之一,這取決於系統默認區域設置的排序順序:

  • -1,如果 stringVar 排在 stringExp 之前。

  • +1,如果 stringVar 排在 stringExp 的后面。

  • 如果兩個字符串相等,則為 0(零)。

示例
 

下面的代碼演示如何使用 localeCompare

 
var str1 = "def";
var str2 = "abc"

document.write(str1.localeCompare(str2) + "<br/>");

// Output: 1
var str3 = "ghi";

document.write(str1.localeCompare(str3)+ "<br/>");

// Output: -1
var str4 = "def";

document.write(str1.localeCompare(str4));

// Output: 0

下面的代碼顯示如何使用具有德語(德國)區域設置的 localeCompare

 
var str1 = "a";
var str2 = "b";

document.write(str1.localeCompare(str2, "de-DE"));

// Output
// - 1

下面的示例顯示如何使用具有德語(德國)區域設置和指定德語電話簿排序順序的區域設置特定擴展的localeCompare。 此示例演示了特定於區域設置的差異。

 
var arr = ["ä", "ad", "af", "a"];

document.write(arr[0].localeCompare(arr[1], "de-DE-u-co-phonebk"));  // Returns 1
document.write (arr[0].localeCompare(arr[2], "de-DE-u-co-phonebk"));  // Returns -1
document.write (arr[0].localeCompare(arr[3], "de-DE-u-co-phonebk"));  // Returns 1

document.write (arr[0].localeCompare(arr[1], "de-DE"));  // Returns -1
document.write (arr[0].localeCompare(arr[2], "de-DE"));  // Returns -1
document.write (arr[0].localeCompare(arr[3], "de-DE"));  // Returns 1

要求
 

 

在以下文檔模式中受支持:Quirks、Internet Explorer 6 標准模式、Internet Explorer 7 標准模式、Internet Explorer 8 標准模式、Internet Explorer 9 標准模式、Internet Explorer 10 標准模式和 Internet Explorer 11 標准模式。此外,也在應用商店應用(Windows 8 和 Windows Phone 8.1)中受支持。請參閱版本信息

locales 和 options 參數:

 

在 Internet Explorer 11 標准文檔模式下支持此項。此外,也在應用商店應用(Windows 8.1 和 Windows Phone 8.1)中受支持。請參閱版本信息

在以下文檔模式中不受支持:Quirks、Internet Explorer 6 標准模式、Internet Explorer 7 標准模式、Internet Explorer 8 標准模式、Internet Explorer 9 標准模式和 Internet Explorer 10 標准模式。在 Windows 8 中不受支持。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM