JavaScript toUpperCase() 方法



JavaScript String 的toUpperCase()方法將字串中的所有字元轉換為大寫字母。它不會改變原始字串,而是返回一個新字串。如果原始字串已經是大寫,則不會進行任何更改。

語法

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

toUpperCase()

引數

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

返回值

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

示例 1

以下示例演示了 JavaScript String toUpperCase() 方法的用法。它將字串“tutorialspoint”的字元轉換為大寫字母。

<html>
<head>
<title>JavaScript String toUpperCase() Method</title>
</head>
<body>
<script>
   const original_str = "tutorialspoint";
   document.write("Original string is: ", original_str);
   const uppercase_str = original_str.toUpperCase();
   document.write("<br>New string(after converting into uppercase) is: ", uppercase_str);
</script>
</body>
</html>

輸出

上述程式在輸出中返回“TUTORIALSPOINT”:

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

示例 2

讓我們取兩個字串“hello”和“HELLO”,並將其中一個“hello”轉換為大寫字母。然後,我們將比較它們並列印一個語句。如果兩個字串相同,則語句為“Equal”,如果它們不同,則語句為“Not Equal”。

<html>
<head>
<title>JavaScript String toUpperCase() Method</title>
</head>
<body>
<script>
   const str1 = "hello";
   const str2 = "HELLO";
   document.write("str1 = ", str1);
   document.write("<br>str2 = ", str2);
   document.write("<br>Before conversion:<br>");
   if(str1 === str2){
      document.write("Equal");
   }
   else{
      document.write("Not Equal");
   }
   document.write("<br>After conversion:<br>");
   if(str1.toUpperCase() === str2){
      document.write("Equal");
   }
   else{
      document.write("Not Equal");
   }
</script>
</body>
</html>

輸出

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

str1 = hello
str2 = HELLO
Before conversion:
Not Equal
After conversion:
Equal

示例 3

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

<html>
<head>
<title>JavaScript String toUpperCase() 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 uppercase: ");
   document.write(str.charAt(9).toUpperCase());
</script>
</body>
</html>

輸出

上述程式將特定字元 'p' 轉換為大寫。

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