LeetCode: Length of Last Word — JavaScript

Vakas Akhtar
2 min readFeb 9, 2021

In this article I’ll be going over the leetcode question length of last word. In this problem the main topic it will cover are strings. Here’s the breakdown of the problem.

Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.A word is a maximal substring consisting of non-space characters only.Example 1:Input: s = "Hello World"
Output: 5
Example 2:Input: s = " "
Output: 0

So looking at this problem it says that the words are separated by spaces. So the logical thing is to use the .split() method in order to break the string up into separate words. An edge case that could occur is that there may be excess white space that could throw off the .split() method that we plan to use. In order to combat that we’ll also use the .trim() method which removes all unnecessary white space at the beginning and end of the string. So let’s get started with our code

var lengthOfLastWord = function(s) {
const wordArray = s.trim().split(/(\s+)/)
}

Now what we have so far is that we’ve chained these methods together to remove any excess white space and then create an array of all the words inside the string. Inside the .split() method it is given the argument /(\s+)/ this is a regular expression or regex that represents white space. By giving .split() this argument it is being set as the delimiter and will split the strings by whitespace into a new array that we’ll call wordArray as separated words. Now that we know we’ll need the last index of this array since we are looking for the length of the last word let’s set a variable that we can use to retrieve the last index of the array.

var lengthOfLastWord = function(s) {
const wordArray = s.trim().split(/(\s+)/)
const last = wordArray.length - 1
}

Now we can put these two variables to use as we set up a conditional statement that will return the length of the last word as long as it is not empty. If it is empty we’ll return 0.

var lengthOfLastWord = function(s) {
const wordArray = s.trim().split(/(\s+)/)
const last = wordArray.length - 1
if (wordArray[last] === ''){
return 0
}else {
return wordArray[last].length
}
}

Congratulations! We now have our solution. You can go head and create or run whatever test cases you’d like to test the code!. The key takeaways here are how to use the .split() and .trim() methods to manipulate the string along with how to find the length of a string.

--

--