JS Sort: Use of the Localecompare () method

Source: Internet
Author: User

Definition: Compares two strings in a local-specific order.

Grammar:stringObject.localeCompare(target)

Parameters: target--The string to be compared with stringobject in a local-specific order.

Return value: A number that describes the result of the comparison.

(1) If Stringobject is less than target, Localecompare () returns a number less than 0.

(2) If Stringobject is greater than target, the method returns a number greater than 0.

(3) If two strings are equal, or if there is no difference based on local collation, the method returns 0.

Description: When you apply the < and > operators to Strings, they compare strings with only Unicode encoding of characters, regardless of local collation. The order generated in this way is not necessarily correct. The Localecompare () method provides a way to compare strings, taking into account the default local collation. The ECMAscript standard does not specify how to perform local-specific comparison operations, it only specifies that the function takes the collation provided by the underlying operating system.

Instance: You can use the Localecompare () method to sort Chinese alphabetically by pinyin, which is quite simple

 var  array = [ "  dove   ", "   Sparrow   ", "   elephant   ", "   dog   ", "   cat   ", "   chicken   " ];array  = Array.Sort (function comparefunction ( Item1, item2) { return   Item1.localecompare    (ITEM2); });

The results are shown as:

[" pigeon "" elephant  " " dog "" Chicken"  " Sparrow  " " cat "

And the following code can be implemented in Chinese according to phonetic sorting, and can be Chinese according to A,b,c,d ... Be differentiated. The code is as follows:

JS Sort: Use of the Localecompare () method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.