To find the length of a String in JavaScript we can use the JavaScript String length property. The length property will return the length of the string, and if the string is empty, it will return 0.
var stringLength = "This is a String".length;
The above code would return the number 16.
Some other examples of length property are below:
var str1 = "This-is-a-String".length;
var str2 = "ThisisaString".length;
var str3 = "".length;
var str4 = "This String has numbers 01239".length;
Which would result in the following:
str2 = 13
str3 = 0
str4 = 29
An example of using the length property in JavaScript to check if the String in an input is empty on a form
Below we will have a simple form with a name field and a submit button. One thing that is common in a lot of online forms is making sure the input fields are filled out before allowing the user to submit the form.
So below we will have a form that only lets you submit the information if you enter in a name in the name input box. Here is the HTML code:
We will use the value property along with the getElementById method to get the value of the input. We will then use the length property to check if the input value is empty or not. If the value is not empty, we will enable the button to be clicked.
We will finally use JavaScript to disable or enable the submit button based on whether a name exist or not. The submit button will start as disabled, and once someone starts typing a name, we will enable the button. We will do this with the help of the onkeyup event.
Here is the code:
function checkString(){
if (document.getElementById("fname").value.length != 0) {
// input is Not empty, enable button
document.getElementById("button1").disabled = false;
} else {
// input is empty, disable button
document.getElementById("button1").disabled = true;
}
};
The final code and output for this example is below:
Code Output:
Full Code:
<script>
function checkString(){
if (document.getElementById("fname").value.length != 0) {
// input is Not empty, enable button
document.getElementById("button1").disabled = false;
} else {
// input is empty, disable button
document.getElementById("button1").disabled = true;
}
};
</script>
Hopefully this article has been useful to help you understand how to find the length of a String in JavaScript.