Welcome to WebmasterWorld Guest from 54.161.110.186

Forum Moderators: open

Message Too Old, No Replies

split() and pop()

separator and end of line

     
7:06 pm on Feb 29, 2012 (gmt 0)

5+ Year Member



I'm learning to use String methods with RegExp object. I have:

mystr = 'Cinnamon, 1223, Peach, 1224, Jasmine, 1225, Pumpkin, 1226, Apple, 1227';

myre = /[^a-z]+/i; //split on

var arr = mystr.split(myre);

console.log(arr):
["Cinnamon", "Peach", "Jasmine", "Pumpkin", "Apple", ""]


Notice the empty element thingy, the output I want is:

["Cinnamon", "Peach", "Jasmine", "Pumpkin", "Apple"]


So I've tried this:


arr = mystr.split(/[^a-z]+/i);
arr.pop();

console.log(arr);
//["Cinnamon", "Peach", "Jasmine", "Pumpkin", "Apple"]


Which gives me what I want but my question is: is this the accepted way to handle a str.split() when the 'separator' is at the end of the string? I'm assuming this must happen often enough to warrant a standard way.

One last thing, I tried doing:


arr = mystr.split(/[^a-z]+/i).pop();


As shown in this forum and other places, but when I look in console.log it tells me 'empty string'. Thanks all.
3:32 am on Mar 1, 2012 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



arr = mystr.split(/[^a-z]+/i).pop()


is equiv to

var temp = mystr.split(/[^a-z]+/i);
arr = temp.pop();

the last item is removed from temp.
pop() returns the removed item, hence empty string.
5:15 pm on Mar 1, 2012 (gmt 0)

5+ Year Member



Thanks daveVk. That makes sense, if there was a way to 'walk thru' each regular expression step in Firefox Firebug then that would help (btw, is there?).

So is there a way to make...


arr = mystr.split(/[^a-z]+/i);
arr.pop();


... an elegant one-liner?
3:00 am on Mar 2, 2012 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



( arr = mystr.split(/[^a-z]+/i) ).pop();

would probably work, elegant I wonder ?

On a tangent, this regEx look a bit fragile, eg "blue berry" comes out as "blue" and "berry".
9:27 am on Mar 2, 2012 (gmt 0)

5+ Year Member



( arr = mystr.split(/[^a-z]+/i) ).pop();

Works, thanks; and just needed to add a space in the regex to fix the Blue Berry.


mystr = 'Cinnamon, 1223, Peach, 1224, Jasmine, 1225, Pumpkin, 1226, Apple Spice, 1227, Blue Berry, 0420';
myre = /[^a-z]+ /i;//split on

//gives
["Cinnamon", "Peach", "Jasmine", "Pumpkin", "Apple Spice", "Blue Berry"]

;)
 

Featured Threads

Hot Threads This Week

Hot Threads This Month