Reputation: 313
Is there a way to obtain all characters that are after the last space in a string?
Examples:
"I'm going out today".
I should get "today"
.
"Your message is too large".
I should get "large"
.
Upvotes: 3
Views: 4926
Reputation: 334
use string.lastIndexOf():
var text = "I'm going out today";
var lastIndex = text.lastIndexOf(" ");
var result = '';
if (lastIndex > -1) {
result = text.substr(lastIndex+1);
}
else {
result = text;
}
UPDATE: Comment edited to add check if there's no space in the string.
Upvotes: 3
Reputation: 3039
var x = "Your message is too large";
function getLastWord(str){
return str.substr(str.lastIndexOf(" ") + 1);
}
alert(getLastWord(x)); // output: large
// passing direct string
getLastWord("Your message is too large"); // output: large
Upvotes: 4
Reputation: 409
try this:
var str="I'm going out today";
var s=str.split(' ');
var last_word=s[s.length-1];
Upvotes: 4
Reputation: 382274
You can do
var sentence = "Your message is too large";
var lastWord = sentence.split(' ').pop()
Result : "large"
Or with a regular expression :
var lastWord = sentence.match(/\S*$/)[0]
Upvotes: 10