localeCompare() – Khuyên dùng cho sắp xếp/so sánh locale
const str1 = "World";
const str2 = "World";
const result = str1.localeCompare(str2); // 0 (bằng nhau)
"Apple".localeCompare("Banana"); // -1 (Apple < Banana)
"Banana".localeCompare("Apple"); // 1
Trả về
0: bằng nhau
-1: str1 < str2 (theo locale)
1: str1 > str2
So sánh bằng (===) – Cho equality check
"hello" === "hello" // true
"hello" === "Hello" // false (case-sensitive)
localeCompare options
// Case insensitive
"Apple".localeCompare("apple", undefined, { sensitivity: 'base' }); // 0
// Numeric sorting
"2".localeCompare("10", undefined, { numeric: true }); // -1 (2 < 10)
"2".localeCompare("10"); // 1 (lexicographic: "2" > "1")
Khi nào dùng gì?
| Cần | Dùng |
| Kiểm tra bằng nhau (case-sensitive) | === |
| Kiểm tra bằng nhau (case-insensitive) | toLowerCase() === hoặc localeCompare(..., {sensitivity:'base'}) |
| Sắp xếp mảng string (locale-aware) | arr.sort((a,b) => a.localeCompare(b)) |
| Sắp xếp có số | localeCompare(..., {numeric:true}) |
Ví dụ hoàn chỉnh
<button onclick="compareStr()">Compare</button>
<p id="test"></p>
<script>
function compareStr() {
var s1 = "World", s2 = "World";
var result = s1.localeCompare(s2);
document.getElementById("test").innerHTML = result; // 0
}
</script>