最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get characters before last space in string - Stack Overflow

programmeradmin1浏览0评论

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".

Share Improve this question edited Jan 20, 2014 at 18:56 Denys Séguret 382k90 gold badges810 silver badges775 bronze badges asked Jan 14, 2014 at 13:47 AlbertoAlberto 3131 gold badge5 silver badges17 bronze badges 5
  • 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
Add a comment  | 

4 Answers 4

Reset to default 10

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]

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.

发布评论

评论列表(0)

  1. 暂无评论