JavaScript String length(或 string.length)属性用于查找当前字符串中存在的字符数。
在 JavaScript 中,字符串是表示字符序列的数据类型。字符串可以由字母、数字、符号、单词或句子组成。
语法
以下是 JavaScript String length 属性的语法 -
在这里,字符串是指要查找其长度的给定字符串。
参数
它不接受任何参数。
返回值
此属性返回字符串的长度,即字符串中存在的字符数。
示例 1
如果给定的字符串为空,它将返回零 (0) 作为字符串长度。
在下面的程序中,我们使用 JavaScript String length 属性来查找空字符串 (“”) 的长度。
输出
上述程序将字符串长度返回为 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,因为它将单词之间的空格视为字符。
输出
执行上述程序后,它将返回字符串的长度为 -
The given string: qikepu com
Length of the given string: 10
Length of the given string: 10
示例 3
如果给定的字符串为空但包含空格,它会将所有空格视为字符并返回字符串的长度。
在下面的示例中,我们使用 string.length 属性来检索字符串 “ ” 的长度(仅包含空格)。
输出
执行上述程序后,它将返回字符串长度。
The given string:
Length of the given string: 4
Length of the given string: 4
示例 4
让我们使用 string.length 属性比较字符串长度,并在条件语句中使用结果来检查字符串的长度是否相等。
输出
以下是上述程序的输出 -
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