JavaScript String length Property
The JavaScript length
property is a fundamental feature used to determine the number of characters in a string. It is essential for various string operations, such as validation, manipulation, and iteration. Understanding how to effectively use the length
property can simplify tasks like checking input lengths, truncating strings, and dynamically adjusting content. This guide provides an overview of the length
property, its usage, and practical examples to enhance your JavaScript programming skills.
Syntax:
string.length
Below are examples of the string length Property.
Example 1: In the first example, 13 is the number of characters in the string “w3wiki”, hence the output is 13. And likewise in the second example, the length of the array is 9 and so is the output
// JavaScript to illustrate length property
function func() {
// length property for string
console.log("GFG".length)
}
func();
Output
3
Example 2: This example returns the length of the given string and the array.
// JavaScript to illustrate length property
function func() {
// length property for array
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9].length);
// length property for string
console.log("w3wiki".length)
}
func();
Output
9 13
Example 3: The example we declare an empty string emptyString. It checks if the length of the string is equal to 0, returning true.
let emptyString = '';
console.log(emptyString.length === 0);
Output
true
Example 4: In the example, we declare a string str with the value ‘w3wiki’. It calculates the index of the last character by subtracting 1 from the string’s length. The lastIndex is then printed, which is 13.
let str = 'w3wiki';
const lastIndex = str.length - 1;
console.log(lastIndex);
Output
12
Utilizing the JavaScript length
property is crucial for efficient string manipulation and validation. Whether you’re handling user inputs, processing data, or dynamically adjusting content, mastering the length
property will streamline your coding process. Explore various use cases and examples to fully leverage this property in your JavaScript projects, ensuring accurate and efficient string operations.
We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.
Supported Browser:
- Chrome
- Edge
- Firefox
- Opera
- Safari
Contact Us