如何在JavaScript中使用當前區域設定比較兩個字串?
在本教程中,我們將學習如何在JavaScript中使用當前區域設定比較兩個字串。區域設定指的是本地位置或地區。在這裡,我們需要根據特定區域設定的語言來比較兩個字串。
通常,當用戶使用等號或嚴格等號運算子比較字串時,它不會根據當前區域設定比較字串。因此,我們將學習如何根據特定區域設定的語言來比較兩個字串。
使用localeCompare()方法比較兩個字串
String 的localeCompare()方法根據瀏覽器的語言(即當前區域設定)比較字串與參考字串。它是一個物件方法,因此使用者需要使用參考字串呼叫該方法,並將第二個字串作為引數傳遞。
語法
我們可以按照以下語法使用localeComapre()方法。
str1.localeCompare(str2);
引數
str1 − 這是一個參考字串,始終是必需的。
str2 − 這是一個引數字串;使用者需要將其與參考字串進行比較。
返回值
- 0 − 如果兩個字串相等。
- 1 − 如果參考字串大於引數字串。
- -1 − 如果參考字串小於引數字串。
示例
在下面的示例中,我們建立了函式comapreString(),它接受兩個字串作為引數,並在比較兩個字串後呈現輸出。在函式內部,我們使用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>
我們已經學習瞭如何根據指定的區域設定比較兩個字串。如果我們沒有指定區域設定,它將採用瀏覽器的預設語言並以此為基礎比較字串。此外,使用者可以使用數學運算子來比較兩個字串。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP