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
广告

© . All rights reserved.