JavaScript 字符串 length 属性
JavaScript 字符串的 length(或 string.length)属性用于查找当前字符串中存在的字符数。
在 JavaScript 中,string 是一种表示字符序列的 数据类型。字符串可以由字母、数字、符号、单词或句子组成。
语法
以下是 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

