Finding the length of second last word in a sentence in JavaScript

A sentence is just a string which contains strings (called words) joined by whitespaces. We are required to write a JavaScript function that takes in one such sentence string and count the number of characters in the second to last word of the string. If the string contains no more than 2 words, our function should return 0.

For example −

If the input string is −

const str = 'this is an example string';

Then the output should be −

const output = 7;

because the number of characters in "example" is 7.

Approach

The solution involves splitting the sentence into words, checking if there are enough words, and returning the length of the second-to-last word:

  1. Split the string into an array of words using split(' ')
  2. Check if the array has more than 2 words
  3. Access the second-to-last word using array[length - 2]
  4. Return its length

Example

Following is the code −

const str = 'this is an example string';

const countSecondLast = (str = '') => {
    const strArr = str.split(' ');
    const { length: len } = strArr;
    
    if(len <= 2){
        return 0;
    };
    
    const el = strArr[len - 2];
    const { length } = el;
    return length;
};

console.log(countSecondLast(str));

Output

7

Testing Different Cases

Let's test the function with various input scenarios:

const countSecondLast = (str = '') => {
    const strArr = str.split(' ');
    const { length: len } = strArr;
    
    if(len <= 2){
        return 0;
    };
    
    const el = strArr[len - 2];
    const { length } = el;
    return length;
};

// Test cases
console.log(countSecondLast('hello world'));           // 0 (only 2 words)
console.log(countSecondLast('JavaScript is awesome')); // 2 (length of "is")
console.log(countSecondLast('one'));                   // 0 (only 1 word)
console.log(countSecondLast('coding in JavaScript is fun')); // 10 (length of "JavaScript")

Output

0
2
0
10

Alternative Approach

Here's a more concise version of the same logic:

const countSecondLastConcise = (str = '') => {
    const words = str.split(' ');
    return words.length <= 2 ? 0 : words[words.length - 2].length;
};

console.log(countSecondLastConcise('this is an example string'));
console.log(countSecondLastConcise('hello world'));

Output

7
0

Conclusion

Finding the length of the second-to-last word requires splitting the sentence into words and checking array bounds. The function returns 0 for sentences with 2 or fewer words, making it safe for edge cases.

Updated on: 2026-03-15T23:19:00+05:30

532 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements