JavaScript toLowerCase() 方法



JavaScript 的 `toLowerCase()` 方法將字串中的所有字元轉換為小寫字母。它不會更改原始字串,而是返回一個新字串。

語法

以下是 JavaScript String toLowerCase() 方法的語法:

toLowerCase()

引數

  • 此方法不接受任何引數。

返回值

此方法返回一個所有字元都小寫的新字串。

示例 1

以下示例演示了此方法的用法。它將字串 "TUTORIALSPOINT" 的字元轉換為小寫字母。

<html>
<head>
<title>JavaScript String toLowerCase() Method</title>
</head>
<body>
<script>
   const original_str = "TUTORIALSPOINT";
   document.write("Original string is: ", original_str);
   const lowercase_str = original_str.toLowerCase();
   document.write("<br>New string(after converting into lowercase) is: ", lowercase_str);
</script>
</body>
</html>

輸出

以上程式的輸出為 "tutorialspoint":

Original string is: TUTORIALSPOINT
New string(after converting into lowercase) is: tutorialspoint

示例 2

讓我們比較兩個字串,其中一個字串 "HELLOWORLD" 轉換為小寫字母,並根據滿足的條件顯示語句。

<html>
<head>
<title>JavaScript String toLowerCase() Method</title>
</head>
<body>
<script>
   const str1 = "helloworld";
   const str2 = "HELLOWORLD";
   document.write("str1 = ", str1);
   document.write("<br>str2 = ", str2);
   document.write("<br>Before conversion:<br>");
   if(str1 === str2){
      document.write("String str1 and str2 are equal");
   }
   else{
      document.write("String str1 and str2 are not equal");
   }
   document.write("<br>After conversion:<br>");
   if(str1 === str2.toLowerCase()){
      document.write("String str1 and str2 are equal");
   }
   else{
      document.write("String str1 and str2 are not equal");
   }
</script>
</body>
</html>

輸出

執行上述程式後,將顯示以下語句:

str1 = helloworld
str2 = HELLOWORLD
Before conversion:
String str1 and str2 are not equal
After conversion:
String str1 and str2 are equal

示例 3

讓我們使用 charAt()toLowerCase() 方法將字串中的特定字元轉換為小寫。在此示例中,我們使用 charAt() 方法檢索字串中的特定字元,並嘗試使用 toLowerCase() 方法將其轉換為小寫。

<html>
<head>
<title>JavaScript String toLowerCase() Method</title>
</head>
<body>
<script>
   const str = "TutorialsPoint";
   document.write("String str = ", str);
   document.write("<br>After converting a specific character '", str.charAt(9), "' into in lowercase: ");
   document.write(str.charAt(9).toLowerCase());
</script>
</body>
</html>

輸出

以上程式將特定字元 'P' 轉換為小寫。

String str = TutorialsPoint
After converting a specific character 'P' into in lowercase: p
廣告