JavaScript - Length of a String
These are the following ways to Find the Length of a String in JavaScript:
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.
let s = "abcd";
console.log(s.length);
Using For Loop
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.
let s = "abcd";
let l = 0;
for (let x in s) {
l++;
}
console.log(l);
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.
function fun(s) {
if (s === "") {
return 0;
} else {
return 1 + fun(s.slice(1));
}
}
console.log(fun("abcd"));
Using the Spread Operator and reduce() Method
Another approach to determine the length of a given string in JavaScript is by utilizing the spread operator (...) along with the reduce() method. This method is less conventional but demonstrates the flexibility of JavaScript in processing strings and arrays.
const s = "abcd!";
const l = [...s].reduce(c => c + 1, 0);
console.log(l);