![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements