< Back to Data Structures and Algorithms
LeetCode 58 ยท Strings
Length of Last Word
How long the last word is, once trailing spaces are trimmed and the rest split into words.
Step through it
Examples
Edge cases
- 0
- 1
- 2
- f3
- l4
- y5
- 6
- m7
- e8
- 9
- 10
- 11
- t12
- o13
- 14
- 15
- 16
- t17
- h18
- e19
- 20
- m21
- o22
- o23
- n24
- 25
- 26
Output
returns 4
โ the expected answer
The code
/**
* Determine the length of the last word in a string.
* @param {string} s
* @return {number}
*/
const lengthOfLastWord = s => {
/* Create an array of words using:
- .trimEnd() to remove trailing whitespace.
- .split(' ') to create the array of words, splitting at each space in the string. */
const words = s.trimEnd().split(' ')
// The last word is the last entry in the words array.
const lastWord = words[words.length-1]
return lastWord.length
}