Could you translate this expression to words?
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
If you did that one step at a time:
var someString = "Hello, how are you today?"; var words = someString.split(/\s+/);
words is the array:
["Hello,", "how", "are", "you", "today?"]
var lastWord = words.pop();
lastWord is the last item from the array, i.e.,
.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
MDN has more information about
Another way to get the last word from a string is as follows:
var lastWord = someString.substr( someString.lastIndexOf(" ") + 1 );
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'
©2020 All rights reserved.