## DEV Community is a community of 848,284 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

duccanhole

Posted on

# code every with me

## --DAY 11--

Hi, I am going to make #100DaysOfCode Challenge. Everyday I will try solve 1 problem from leetcode or hackerrank. Hope you can go with me until end.
Now let's solve problem today:
-Problem: Length of Last Word
-Detail: here
-Idea: I will use string string method in javascript to solve it
+) Use `split()` to split string into array
+) `trim()` to remove space of the last word
+) Return it's length
->So simple, right?
-My solution (javascript):

``````var lengthOfLastWord = function(s) {
s=s.trim().split(' ');
return s[s.length-1].trim().length;
};
``````

-->If you have better solution or any question, please comment below. I will appreciate.

## Discussion (4)

Frank Wisniewski
``````const lengthOfLastWord=s=>(s)?s.match(/^.*\b(\w+)/)[1].length:0

console.log(lengthOfLastWord('the last word ')) //->4
console.log(lengthOfLastWord('')) //->0
console.log(lengthOfLastWord()) //->0

const lengthOfLastWord1 = function(s) {
s=s.trim().split(' ');
return s[s.length-1].trim().length;
};

console.log(lengthOfLastWord1('the last word ')) //->4
console.log(lengthOfLastWord1('')) //->0
console.log(lengthOfLastWord1()) //->TypeError

const lengthOfLastWord2 = function(s) {
s = s.trim().split(' ');
return (s[s.length-1].length);
};

console.log(lengthOfLastWord2('the last word ')) //->4
console.log(lengthOfLastWord2('')) //->0
console.log(lengthOfLastWord2()) //->TypeError
``````
Frank Wisniewski
``````console.log ((" The last word ".match(/^.*\b(\w+)/)[1]).length)
``````
sherifhegazy

// there is no need for the second trim

var lengthOfLastWord = function(s) {
s = s.trim().split(' ');

return (s[s.length-1].length);

};

duccanhole

oh, I didn't notice that. Thanks !