JavaScript Objects: Strings - Length Property
(Page 2 of 6 )
The length property returns the number of characters in a string. Pretty simple. Here it is used in code:
<html>
<body>
<p>COMPUTAR R SMARTE IT TELL NUMBER OF PERTY LETERS:<br /><br /></p>
<script type="text/javascript">
var longword="Look how long this string is weeeeeeeee!"
document.write(longword.length)
</script>
</body>
</html>
This code would display:
COMPUTAR R SMARTE IT TELL NUMBER OF PERTY LETERS:
40
Note that the Length also includes the number of spaces in the string.
In this example we will create two variables with words in them, display the number of characters in each word, then display how many more letters the larger word has than the smaller word:
<html>
<body>
<p>COMPUTAR R SMARTE IT TELL NUMBER OF PERTY LETERS:<br /><br /></p>
<script type="text/javascript">
var longword="Googleplex"
var shortword="Cat"
document.write("The word Googleplex has this many letters: ")
document.write(longword.length)
document.write("<br />The word Cat has this many letters: ")
document.write(shortword.length)
document.write("<br />Googleplex has this many more letters: ")
document.write(longword.length - shortword.length)
</script>
</body>
</html>
This will result in the following print out:
COMPUTAR R SMARTE IT TELL NUMBER OF PERTY LETERS:
The word Googleplex has this many letters: 10
The word Cat has this many letters: 3
Googleplex has this many more letters: 7
Next: Prototype >>
More JavaScript Articles
More By James Payne