如何在 JavaScript 中使用當前區域設定比較兩個字串?
在本教程中,我們將學習如何使用 JavaScript 在當前區域設定下比較兩個字串。區域設定指的是本地位置或地區。在這裡,我們需要根據特定區域設定的語言來比較兩個字串。
通常,當用戶使用相等或嚴格相等運算子比較字串時,它不會根據當前區域設定比較字串。因此,我們將學習如何根據特定區域設定的語言來比較兩個字串。
使用 localeCompare() 方法比較兩個字串
String 的localeCompare()方法根據瀏覽器的語言(即當前區域設定)比較字串與參考字串。它是一個物件方法,因此使用者需要使用參考字串呼叫該方法,並將第二個字串作為引數傳遞。
語法
我們可以按照以下語法使用 localeCompare() 方法。
str1.localeCompare(str2);
引數
str1 − 這是參考字串,始終是必需的。
str2 − 這是引數字串;使用者需要將其與參考字串進行比較。
返回值
- 0 − 如果兩個字串相等。
- 1 − 如果參考字串大於引數字串。
- -1 − 如果參考字串小於引數字串。
示例
在下面的示例中,我們建立了函式compareString(),它以兩個字串作為引數,並在比較兩個字串後呈現輸出。在函式內部,我們使用的是localeCompare()方法。
<html> <head> </head> <body> <h2> Compare two strings with current locale. </h2> <h4> Comparing strings using <i> localeCompare </i> method. </h4> <p id = "output"> </p> <script> let output = document.getElementById("output"); let str1 = "hello"; let str2 = "TutorialsPoint"; function compareStrings(str1, str2) { let result = str1.localeCompare(str2); if (result == 0) { output.innerHTML += str1 + " == " + str2 + "<br/>"; } else if (result == 1) { output.innerHTML += str1 + " > " + str2 + "<br/>"; } else { output.innerHTML += str1 + " < " + str2 + "<br/>"; } } compareStrings(str1, str2); compareStrings("abc", "abc"); </script> </body> </html>
在上面的輸出中,使用者可以看到字串“TutorialPoint”的字母順序高於字串“hello”。
在不同區域設定中比較兩個字串
在本方法中,我們將使用相同的方法 localeCompare() 來匹配字串,但我們將更改當前區域設定並根據不同的區域語言比較字串。此外,我們將傳遞一些選項作為 localeCompare() 方法的引數,以根據選項比較字串。
語法
使用者可以按照以下語法在 localeCompare() 方法中使用不同的區域設定。
let str1 = "'Hello programmers!'"; let str2 = "Welcome, here."; let options = { ignorePunctuation: true } let result = str1.localeCompare(str2, "en-US", options);
引數
en-US − 這是一個基於區域語言的區域設定,使用者希望根據該區域設定比較兩個字串。這是一個可選引數。“en-US”表示美國地區的英語。我們可以為不同的區域設定新增不同的程式碼。
options − 這也是一個可選引數,包含用於比較字串的不同選項。在本例中,在比較字串時,它將忽略標點符號。
示例
在下面的示例中,我們根據 en-US 區域設定比較兩個字串。此外,我們在比較字串時忽略標點符號。
<html> <head> </head> <body> <h2> Comparing two strings with current locale. </h2> <h4> comparing strings in different locale using <i>localeCompare</i> method. </h4> <p id = "output"> </p> <script> let output = document.getElementById("output"); let str1 = "'Hello programmers!'"; let str2 = "Welcome, here."; function compareStrings(str1, str2) { let options = { ignorePunctuation: true } let result = str1.localeCompare(str2, "en-US", options); if (result == 0) { output.innerHTML += str1 + " == " + str2 + "<br/>"; } else if (result == 1) { output.innerHTML += str1 + " > " + str2 + "<br/>"; } else { output.innerHTML += str1 + " < " + str2 + "<br/>"; } } compareStrings(str1, str2); </script> </body> </html>
我們學習瞭如何根據指定的區域設定比較兩個字串。如果我們不指定區域設定,它將採用瀏覽器的預設語言並基於該語言比較字串。此外,使用者可以使用數學運算子來比較兩個字串。