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

javascript - Get part of string into variable - Stack Overflow

programmeradmin0浏览0评论

i need to get part of string into variable. (note, i will always use exactly 4 names)

var names = "Andrew Peter Bob Mark"

I need to get the last one to

var last = "Mark"

Thanks for help in advance

i need to get part of string into variable. (note, i will always use exactly 4 names)

var names = "Andrew Peter Bob Mark"

I need to get the last one to

var last = "Mark"

Thanks for help in advance

Share Improve this question asked Feb 17, 2010 at 13:39 user270158user270158 4412 gold badges5 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5
var last = names.split(/\s+/).pop(); // "Mark"

Explanation: .split splits a string on a given separator and returns an array. /\s+/ is a regular expression for "one or more whitespaces" (space, tab, newline, etc). .pop() grabs the last value from the array that .split returns.

Answer from Roatin Marth is correct, but in case if you need 4 times faster version (in IE) of same operation:

var last = names.substr(names.lastIndexOf(" "));

It is working without regular expressions and temp arrays - just with index operations of string.

发布评论

评论列表(0)

  1. 暂无评论