DEV Community

duccanhole
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;
};
Enter fullscreen mode Exit fullscreen mode

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

Top comments (4)

Collapse
 
frankwisniewski profile image
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
Enter fullscreen mode Exit fullscreen mode
Collapse
 
frankwisniewski profile image
Frank Wisniewski
console.log ((" The last word ".match(/^.*\b(\w+)/)[1]).length)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sherifhegazy profile image
sherifhegazy

// there is no need for the second trim

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

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

};

Collapse
 
coderduck profile image
duccanhole

oh, I didn't notice that. Thanks !