I have a string
var str = "2 Days, 2 Hours 10 Minutes";
if I :
str.split(/Days/);
I get:
["2 ", ", 2 Hours 10 Minutes"]
So I think I can use string.split to split out my string and get the “days”, “hours” and “minutes” with this method.
However, what do I do when I sometimes have “s” or no “s”, for example:
var str = "1 Day, 2 Hours 10 Minutes";
Here my string is “1 Day” not “2 Days” so I don’t have the “s” on the “day” value. Is there a way to split a string on
Day(s)
Hour(s)
Minute(s)
You’re using a Regular Expression to do the split, so simply place a question mark after the ‘s’ to make it optional:
You probably also want to make it case-insensitive by adding the
iflag to the Regex:You could also do the whole thing with a single line using the
matchstring method (instead ofsplit) like this:That will return an array like this:
So the items in positions 1, 2 and 3 are the days, hours and minutes respectively.
To break that Regex down into english:
… and repeat for hours and minutes.
Check the docs for regex matching on strings here, and great docs on how to use regular expressions here.