split(/\\s+/).pop() - what does it do?

2020-03-04 08:28发布

问题:

Could you translate this expression to words?

split(/\s+/).pop()

It is in javascript and uses regex to split a string, but what are the principles?

回答1:

That line of code will split a string on white space to create an array of words, and then return the last word.

Presumably you have seen this used on a string of some kind, e.g.:

var someString = "Hello, how are you today?";
var lastWord = someString.split(/\s+/).pop();

In which case lastWord would be "today?".

If you did that one step at a time:

var someString = "Hello, how are you today?";
var words = someString.split(/\s+/);

Now words is the array: ["Hello,", "how", "are", "you", "today?"]

Then:

var lastWord = words.pop();

Now lastWord is the last item from the array, i.e., "today?".

The .pop() method also actually removes the last item from the array (and returns it), so in my second example that would change words so that it would be ["Hello,", "how", "are", "you"].

If you do it all in one line as in my first example then you don't ever actually keep a reference to the array, you just keep the last item returned by .pop().

MDN has more information about .split().

Another way to get the last word from a string is as follows:

var lastWord = someString.substr( someString.lastIndexOf(" ") + 1 );


回答2:

TLDR:

1)the split part creates an array based on the regex /\s+/ (which means separate by whitespace)

2) the pop part returns the last element of the array

could be rewritten as

var array = "one two three four five".split(/\s+/);
var lastMemberOfArray = array.pop()

I often use split(".").pop() to get file extension

var html = "holidays-and-parties/photos/a-pioneer-halloween.html"
var ext = html.split(".").pop(); // ext now holds 'html'