JavaScript String length(或 string.length)属性用于查找当前字符串中存在的字符数。
在 JavaScript 中,字符串是表示字符序列的数据类型。字符串可以由字母、数字、符号、单词或句子组成。
语法
以下是 JavaScript String length 属性的语法 -
string.length
在这里,字符串是指要查找其长度的给定字符串。
参数
它不接受任何参数。
返回值
此属性返回字符串的长度,即字符串中存在的字符数。
示例 1
如果给定的字符串为空,它将返回零 (0) 作为字符串长度。
在下面的程序中,我们使用 JavaScript 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>
输出
上述程序将字符串长度返回为 0。
The given string:
Length of the given string: 0
Length of the given string: 0
示例 2
以下是 JavaScript String length 属性的另一个示例。我们使用 string.length 属性来查找当前字符串 'qikepu com' 中存在的字符数。
给定的字符串包含 14 个字符,但它将返回字符串长度为 15,因为它将单词之间的空格视为字符。
<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script>
const str = "qikepu com";
document.write("The given string: ", str);
document.write("<br>Length of the given string: ", str.length);
</script>
</body>
</html>
输出
执行上述程序后,它将返回字符串的长度为 -
The given string: qikepu com
Length of the given string: 10
Length of the given string: 10
示例 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
Length of the given string: 4
示例 4
让我们使用 string.length 属性比较字符串长度,并在条件语句中使用结果来检查字符串的长度是否相等。
<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script>
const str1 = "qikepu com";
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 : qikepu com, Hello, World
Length of qikepu com is: 10
Length of Hello is: 5
Length of World is: 5
String Hello and World having equal length
Length of qikepu com is: 10
Length of Hello is: 5
Length of World is: 5
String Hello and World having equal length