Javascript String Length Example
When writing code that has to do with strings and you need to know it’s length, or even find out if your variable is an empty one, you can get this information by finding out how long exactly this string is. Here’s how:
String length
One of the most important built-in properties for string variables in Javascript (and also other programming languages) is length. Have a look at the code snippet below:
var ourString = "The string whose length we're going to find"; alert(ourString.length);
We have firstly declared a non empty string, and then we’ve put out an alert that shows us it’s length, by using the property .length
on it.
If what we want to know whether we have an empty string or not, we run the same code, except instead of the string we have an empty one. It would look like this:
var ourString1 = ""; alert(ourString1.length);
However we can’t use this property to find out if the variable has been set or not, as instead of the length, we’d have an undefined Javascript error.
To avoid this error we can first run a check using the typeOf
method and then find the length if the variable turns out to be a string
, or we can use another method. This one would be by only running the code if the unknown variable we have in our hands is a string and if it is of a certain length. the code would go like this:
var unknownVariable; if ((typeof unknownVariable == "string") && (unknownVariable.length > 0)) { //code here }
This way you can use the length
property whatever way you might need.
Download the source code
This was an example of string length in Javascript.
Download the source code for this tutorial:
You can download the full source code of this example here: StringLength