Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 670
secr Avatar asked Aug 04 '13 01:08

secr


1 Answers

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 );
like image 129
nnnnnn Avatar answered Oct 03 '22 14:10

nnnnnn