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.

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

Following is the console output −

7

Updated on: 20-Jan-2021

279 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements