JavaScript Program to Find the Length of a String
Last Updated :
19 Mar, 2024
Given a String, the task is to find the length of a given string in JavaScript. This task is fundamental in string processing and is commonly encountered in various programming scenarios. The program provides a simple yet effective solution to calculate the length of any string input, enabling developers to assess the string data size accurately.
These are the following approaches:
Using the length Property
This approach directly utilizes the built-in length property of strings in JavaScript, which returns the number of characters in the given string.
Example: This example shows the length of the given string by the use of the .length() method.
Javascript
function findStrLength(str) {
return str.length;
}
// Driver Code
let str = "Hello World";
let len = findStrLength(str);
console.log(len);
Iterative Approach
In this method, iterates over each characters of the string using a loop and increments a counter variable to keep track of the total number of characters.
Example: This example shows the length of the given string by the use of the loop.
Javascript
function findStrLength(str) {
let length = 0;
for (let i = 0; i < str.length; i++) {
length++;
}
return length;
}
// Driver Code
let str = "Hello World";
let len = findStrLength(str);
console.log(len);
Share your thoughts in the comments
Please Login to comment...