JavaScript string comparison method: 1. Directly use ">", "<", "==", "===" operators to compare strings; 2. Use string The localeCompare() method can compare the sizes of two strings according to the local convention order.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
JavaScript can compare string sizes bit by bit based on the character's Unicode encoding size.
Direct comparison of strings
In JavaScript, you can directly use >, <code><
, ==
, ===
to compare the size of two strings, just like comparing two numbers.
For example, the encoding of the lowercase letter a is 97, and the encoding of the uppercase letter A is 65, then the character "a" is greater than "A".
console.log("a" > "A"); //返回true
For another example, the Unicode encoding of "Chinese" is \u4e2d\u56fd\u4eba, and the encoding of "Programming Language" is \u7f16\u7a0b\u8bed\u8a00, because \u4e2d is smaller than \u7f16, so " "Chinese" is smaller than "programming language".
console.log("中国人"<"编程语言"); //返回true
Use the localeCompare() method
Use the localeCompare() method of strings to compare the sizes of two strings according to the local convention order. The ECMAScript standard does not specify how to perform localized comparison operations.
The localeCompare() method contains a parameter specifying the target string to be compared. If the current string is less than the parameter string, it returns a number less than 0; if it is greater than the parameter string, it returns a number greater than 0; if the two strings are equal, or there is no difference from the local sorting convention, the method returns 0.
[Example] The following code converts the string "JavaScript" into an array, and then sorts it in local character order.
var s = "JavaScript"; //定义字符串直接量 var a = s.split(""); //把字符串转换为数组 var s1 = a.sort(function (a, b)) { //对数组进行排序 return a.localeCompare(b); //将根据前后字符在本地的约定进行排序 }); a = s1.join(""); //然后再把数组还原为字符串 console.log(a); //返回字符串“aaciJprStv”
【Related recommendations: javascript learning tutorial】
The above is the detailed content of What are the JavaScript string comparison methods?. For more information, please follow other related articles on the PHP Chinese website!