Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  115] [ 1]  / answers: 1 / hits: 31770  / 11 Years ago, sun, august 4, 2013, 12:00:00

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?


More From » regex

 Answers
4

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 );

[#76537] Friday, August 2, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lara

Total Points: 462
Total Questions: 100
Total Answers: 102

Location: Jersey
Member since Mon, Jun 14, 2021
3 Years ago
lara questions
;