JavaScript Program to Find the Length of a String

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:

Table of Content

  • Using the length Property
  • Iterative Approach
  • Using Recursion

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);

Output
11

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);

Output
11

Using Recursion

Using recursion to find a string’s length involves a base case returning 0 for an empty string and a recursive case adding 1 to the result of calling the function with the string minus its first character. This process continues until the base case is reached.

Example: This example uses recursive approach to find the length of a string.

JavaScript
function getStringLength(str) {
    // Base case: if the string is empty, return 0
    if (str === "") {
        return 0;
    } else {
        // Recursive case: return 1 plus the length of the string 
        //minus the first character
        return 1 + getStringLength(str.slice(1));
    }
}

// Example usage:
console.log(getStringLength("w3wiki"));

Output
13