Get part of a string in a variable

I need to get part of a string in a variable. (note, I will always use exactly 4 names)

var names = "Andrew Peter Bob Mark"

I need to get the last

var last = "Mark"

Thanks for the help in advance.

+3
source share
2 answers
var last = names.split(/\s+/).pop(); // "Mark"

Explanation: .splitsplits the string at the specified delimiter and returns an array. /\s+/is a regular expression for "one or more spaces" (space, tab, newline, etc.). .pop()takes the last value from the array returned .split.

+5
source

Roatin Marth's answer is correct, but if you need 4 times faster version (in IE) of the same operation:

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

temp - .

+3

Source: https://habr.com/ru/post/1733193/


All Articles