Alberto
Alberto

Reputation: 313

Get characters before last space in string

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

Answers (4)

P R
P R

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

Ashish Kumar
Ashish Kumar

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

Prakash R
Prakash R

Reputation: 409

try this:

    var str="I'm going out today";
    var s=str.split(' ');
    var last_word=s[s.length-1];

Upvotes: 4

Denys Séguret
Denys Séguret

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

Related Questions