Reputation: 251
I have an an array containing various timeslots :
var timeArray = ["00:05 - 02:50", "03:05 - 05:50", "05:10 - 07:55", "06:25 - 09:10", "07:55 - 10:40", "09:00 - 11:45", "15:10 - 17:55", "17:05 - 19:45", "18:50 - 21:35", "19:40 - 22:25", "20:45 - 23:40", "22:00 - 00:45", "22:40 - 01:25", "11:55 - 16:15"]
I want to search all the timeslots between 06-12 and push them in an array. I wrote below js but this is returning me an empty array:
var resultArray = new Array();
for (var i = 0; i < timeArray.length; i++) {
var bar = /^06:^07:^08:^09:^10:^11/;
if (bar.test(timeArray[i])) {
alert("found desired timeslots");
resultArray.push(timeArray[i]);
}
};
Upvotes: 4
Views: 187
Reputation: 14611
The regular expression should rather be: ^06|^07|^08|^09|^10|^11
. Another more concise alternative would be: /^0[6-9]|^1[01]/
Runnable example below:
var timeArray = ["00:05 - 02:50", "03:05 - 05:50", "05:10 - 07:55", "06:25 - 09:10", "07:55 - 10:40", "09:00 - 11:45", "15:10 - 17:55", "17:05 - 19:45", "18:50 - 21:35", "19:40 - 22:25", "20:45 - 23:40", "22:00 - 00:45", "22:40 - 01:25", "11:55 - 16:15"]
var resultArray = new Array();
for (var i = 0; i < timeArray.length; i++) {
var bar = /^06|^07|^08|^09|^10|^11/;
if (bar.test(timeArray[i])) {
console.log("found desired timeslots: " + timeArray[i]);
resultArray.push(timeArray[i]);
}
};
Upvotes: 1
Reputation: 386604
You could takes some groups for the wanted times and use only one start indicator.
var timeArray = ["00:05 - 02:50", "03:05 - 05:50", "05:10 - 07:55", "06:25 - 09:10", "07:55 - 10:40", "09:00 - 11:45", "15:10 - 17:55", "17:05 - 19:45", "18:50 - 21:35", "19:40 - 22:25", "20:45 - 23:40", "22:00 - 00:45", "22:40 - 01:25", "11:55 - 16:15"],
resultArray = timeArray.filter(s => /^(0[6-9]|1(0|1))/.test(s));
console.log(resultArray);
Upvotes: 3