Reputation: 8164
I am practicing and I wrote length of last word in JS.
var lengthOfLastWord = function (s) {
var words = s.split(" ");
var len = words.length;
for (let i = 0; i < len; i++) {
if (len == 1){
var last_element = words[0];
}
else {
var last_element = words[len - 1];
}
return last_element.length;
}
}
But it doesn't work well if
s = 'a '
or
s = 'Hello.'
How to write substring to remove everything except characters?
Upvotes: 1
Views: 67
Reputation: 1287
I would suggest you to try the following code:
s = 'Hello. '
s.trim();
The trim()
function removes all whitespaces from your String.
Upvotes: 1
Reputation: 693
You can use regex to replace charachters those are not in a-z
or A-Z
or 0-9
. or simply just use \W
in regex expression :
var last_element = words[len - 1].replace(/\W/g, "");
Upvotes: 1