JavaScript 字串長度屬性



JavaScript 字串的length(或 string.length)屬性用於查詢當前字串中存在的字元數。

在 JavaScript 中,字串是一種資料型別,表示一系列字元。字串可以包含字母、數字、符號、單詞或句子。

語法

以下是 JavaScript 字串length屬性的語法:

string.length

這裡,string 指的是要查詢其長度的給定字串。

引數

  • 它不接受任何引數。

返回值

此屬性返回字串的長度,即其中存在的字元數。

示例 1

如果給定的字串為空,它將返回零 (0) 作為字串長度。

在下面的程式中,我們使用 JavaScript 字串length屬性來查詢字串("")的長度。

<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script>
   const str = "";
   document.write("The given string: ", str);
   document.write("<br>Length of the given string: ", str.length);
</script>
</body>
</html>

輸出

上述程式返回字串長度為 0。

The given string:
Length of the given string: 0

示例 2

以下是 JavaScript 字串length屬性的另一個示例。我們使用string.length屬性查詢當前字串'Tutorials point'中存在的字元數。

給定的字串包含14個字元,但它將返回字串長度為15,因為它將單詞之間的空格視為一個字元。

<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script>
   const str = "Tutorials point";
   document.write("The given string: ", str);
   document.write("<br>Length of the given string: ", str.length);
</script>
</body>
</html>

輸出

執行上述程式後,它將返回字串的長度為:

The given string: Tutorials point
Length of the given string: 15

示例 3

如果給定的字串為空但包含空格,它將所有空格視為字元並返回字串的長度。

在下面的示例中,我們使用string.length屬性檢索字串" "(僅包含空格)的長度。

<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script>
   const str = "    ";
   document.write("The given string: ", str);
   document.write("<br>Length of the given string: ", str.length);
</script>
</body>
</html>

輸出

執行上述程式後,它將返回字串長度。

The given string:
Length of the given string: 4

示例 4

讓我們使用string.length屬性比較字串長度,並在條件語句中使用結果來檢查字串長度是否相等。

<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script>
   const str1 = "Tutorials Point";
   const str2 = "Hello";
   const str3 = "World";
   document.write("The given strings are : ", str1, ", ", str2, ", ", str3);
   const len1 = str1.length;
   const len2 = str2.length;
   const len3 = str3.length;
   document.write("<br>Length of ", str1, " is: ", len1);
   document.write("<br>Length of ", str2, " is: ", len2);
   document.write("<br>Length of ", str3, " is: ", len3);
   if(len1 == len2){
      document.write("<br>String ", str1, " and ", str2, " having equal length");
   }
   else if(len1 == len3){
      document.write("<br>String ", str1, " and ", str3, " having equal length");
   }
   else if(len2 == len3){
      document.write("<br>String ", str2, " and ", str3, " having equal length");
   }
   else{
      document.write("<br>None of the strings having equal length");
   }
</script>
</body>
</html>

輸出

以下是上述程式的輸出:

The given strings are : Tutorials Point, Hello, World
Length of Tutorials Point is: 15
Length of Hello is: 5
Length of World is: 5
String Hello and World having equal length
廣告