It is often necessary to calculate the number of characters within strings for the completion of various different tasks. Javascript offers a simply way for retrieving this value, the
length
property that is included in all string objects.
The
length
property can be used on any string and returns the number of characters present within the string.
Using the string length property
The
basic syntax
for retrieving the length of a string is as follows:
string.length;
This will return the number of characters within the given string as an integer.
As an example, say we wanted to retrieve the number of characters in the string "Hello world" then we could use the following code:
var testString = "Hello world";
var stringLength = testString.length;
The statement "testString.length" will return 11 as a value which will be stored in the stringLength variable for later use as needed.
The length property can also be used directly on a string like so:
var stringLength = "Hello world".length;
The
length
property is compatible across all modern browsers.