简体   繁体   中英

Get part of string into variable

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM