0

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)
redconservatory
  • 21,438
  • 40
  • 120
  • 189

3 Answers3

2

You're using a Regular Expression to do the split, so simply place a question mark after the 's' to make it optional:

str.split(/Days?/);

You probably also want to make it case-insensitive by adding the i flag to the Regex:

str.split(/days?/i);

You could also do the whole thing with a single line using the match string method (instead of split) like this:

("2 Days, 3 hours, 5 minutes").match(/(\d+)\s*days?\,?\s*(\d+)\s*hours?\,?\s*(\d+)\s*minutes?/i)

That will return an array like this:

["2 Days, 3 hours, 5 minutes", "2", "3", "5"]

So the items in positions 1, 2 and 3 are the days, hours and minutes respectively.

To break that Regex down into english:

  • (captured group, i.e. array item 1) 1 or more digits
  • zero or more whitespace characters
  • day
  • optional s
  • optional comma
  • zero or more whitespace characters ... 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.

Jed Watson
  • 20,150
  • 3
  • 33
  • 43
1

Sure:

str.split(/Days?/);
str.split(/Hours?/);
str.split(/Minutes?/);
PinnyM
  • 35,165
  • 3
  • 73
  • 81
1

If you're attempting to get the Days/Hours/Minutes into a single 3 element array and you can guarantee your inputs will always have a value (even if that value is 0), it might be simpler just to eradicate all non-numerics and non-spaces and then split on space and remove empty elements.

var result = new Array();
var tempstr = str.replace(/[^0-9\s]/g, ''); 
var arr = tempstr.split(' ');

for(var i = 0; i<arr.length; i++) {
    if (arr[i]) {
        result.push(arr[i]);
    }
}

Note: Array cleaning loop appropriated from this SO Post.

Community
  • 1
  • 1
Joel Etherton
  • 37,325
  • 10
  • 89
  • 104