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"
.
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"
.
- this almost sounds like homework ;) – JensB Commented Jan 14, 2014 at 13:49
- @JensBerfenfeldt It's an easy thing to do but it's common to have to do it. – Denys Séguret Commented Jan 14, 2014 at 13:50
- 3 After or before the last space? – Bergi Commented Jan 14, 2014 at 13:51
- @dystroy Never said it wasn't easy, just saying that it sounds alot like something someone new might get asked to do as an assignment :) May be my lack of coffee but In what scenarios would you use this outside of assignment purposes? – JensB Commented Jan 14, 2014 at 13:52
- @JensB one example would be doing something like a predictive type, resetting the logic on every space user types in. Also so what if it's an assignment, it is a helpful question. – orpqK Commented Jun 18, 2018 at 22:19
4 Answers
Reset to default 10You 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]
try this:
var str="I'm going out today";
var s=str.split(' ');
var last_word=s[s.length-1];
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
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.