获取字符串中最后一个空格前的字符

时间:2014-01-14 13:47:59

标签: javascript string

有没有办法获取字符串中最后一个空格之后的所有字符?

示例:

"I'm going out today".

我应该"today"

"Your message is too large".

我应该"large"

4 个答案:

答案 0 :(得分:7)

你可以做到

var sentence = "Your message is too large";
var lastWord = sentence.split(' ').pop()

结果:"large"

或使用regular expression

var lastWord = sentence.match(/\S*$/)[0]

答案 1 :(得分:4)

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

答案 2 :(得分:4)

试试这个:

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

答案 3 :(得分:3)

使用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;
}

更新:编辑注释以添加检查字符串中是否没有空格。