Sorting is a function we often encounter in daily development. The following article mainly introduces you to the relevant information about using JavaScript to sort Chinese (Chinese characters) , the article introduces it in detail through sample code, which has certain reference and learning value for everyone. Friends who need it can follow the editor to take a look.
Preface
When displaying a list on a web page, it is often necessary to sort the list: sort by modification/access time, by region, by name Sort.
For Chinese lists, sorting by name is sorting by pinyin, which cannot be achieved simply by string comparison - 'a' > 'b' - this way.
For example, comparing ‘Beijing’ vs ‘Shanghai’ actually compares ‘běijīng’ vs ‘shànghǎi’; comparing ‘Beijing’ vs ‘background’ actually compares ‘běijīng’ vs ‘bèijǐng’.
Generally, you need to obtain the pinyin of the string and then compare the respective pinyin.
Implementation method
JavaScript provides localized text sorting, such as sorting Chinese according to pinyin, without the need for the program to display the pinyin of the comparison string.
<a href="//m.sbmmt.com/wiki/57.html" target="_blank">String</a>.prototype.localeCompare
Without considering polyphonic characters, sorting by pinyin can basically be achieved perfectly.
As long as there are no accidents, all browsers that support localeCompare are normal. Recently, I updated Chrome to 58.0.3029.110, and suddenly found that the Chinese sorting was not normal.
// 正常应该返回 1, 拼音 jia 在前, kai 在后 '开'.localeCompare('驾'); // 得到 -1; // Chrome 58.0.3029.110 下返回 -1, 其他浏览器正常 // 确认之后是 localeCompare 需要明确指定 locales 参数 '开'.localeCompare('驾', 'zh'); // 得到 1
Pass the locales parameter under Chrome to get normal expected results
Edge browser supports localeCompare
Firefox browser supports localeCompare
IE 11 browser supports localeCompare
Other browsers The support for localeCompare is also very friendly. Currently, there is no need to explicitly pass locales. For browser support, please refer to developer.mozilla.org
Summary
The above is the detailed content of Example analysis of sorting Chinese using JavaScript_javascript skills. For more information, please follow other related articles on the PHP Chinese website!