Quick Reach
The string length property of Javascript
The string length property is used to return the length or number of characters in a given string. The JS length property returns int number.
The string length property may be useful is different scenarios like allowing the visitors a limited number of characters in a textarea etc.
See an example of length property
Syntax of using string length method
Following is the string length, javascript property syntax:
Str.length;
Where Str is a string variable. The length property will return a total number of characters of Str variable.
A length property example
Following is a javascript length property example. We have created a string object and then used length JS property. The alert will show total characters or length of string. See example online by clicking the link:
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<!DOCTYPE html>
<html>
<body>
<button onclick=“showalert()”>Show string length</button>
<script type=“text/javascript”>
function showalert(){
var str = “This is length string tutorial!”;
var str_length = str.length;
alert (“The string length is: “ + str_length);
}
</script>
</body>
</html>
|
As you click on the button “Show string length” the alert will show the length of string by using the length property.
String length javascript example with textarea
In this example, we are using a textarea to show the use of length property. Enter some text in textarea and then press the button. The alert will show total characters entered, by using Javascript length property.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<!DOCTYPE html>
<html>
<body>
<textarea id=“jslength” rows=“10” cols=“20”></textarea><br /><br />
<button onclick=“showalert()”>Show string length</button>
<script type=“text/javascript”>
function showalert(){
var str = document.getElementById(“jslength”).value;
var str_length = str.length;
alert (“The string length is: “ + str_length);
}
</script>
</body>
</html>
|
Javascript length example with string concatenation
Following example uses length property, after concatenating two strings. The length method returns total characters after concatenation, as shown below:
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<!DOCTYPE html>
<html>
<body>
<button onclick=“showalert()”>Show string length</button>
<script type=“text/javascript”>
function showalert(){
var str1 = “This is string length tutorial! “;
var str2 = “This is string 2!”;
var str_length = str1 + str2;
alert (“The string length after concat is: “ + str_length.length);
}
</script>
</body>
</html>
|
AS you can see two strings are concatenated and an alert shows total characters after using javascript string length property.
Related Javascript String | Javascript substring | Javascript replace | Javascript Array Length
Leave A Comment?