I have below string :
var deptInfo = "Flight-1 08:30~Flight-1 10:45|Flight-2 15:15~Flight-2 17:30"
I want to have info in the format:
var timeSlot = ["08:30-10:45","15:15-17:30"]
I am trying to split the deptInfo
like this:
var timeSlot = deptInfo.split("(Flight-1 )|(~Flight-1 )").join('-').split('|').join(',').split("(Flight-2 )|(~Flight-2 )").join('-');
var timeSlot = deptInfo.split(/Flight-1 ~Flight-1 /).join('-').split('|').join(',').split(/Flight-2 ~Flight-2 /).join('-');
But this is not delivering the expected results. Can someone please help?
You may use the following pattern to extract the necessary bits and then post-process the matches to get the necessary output:
/(\d{2}:\d{2})~Flight-\d+\s*(\d{2}:\d{2})/g
See the regex demo. Note you may even wrap the pattern with \b
(word boundaries) if you want to make sure the first and last 2 digits are not preceded/followed with a word char, /\b(\d{2}:\d{2})~Flight-\d+\s*(\d{2}:\d{2})\b/g
.
Details
(\d{2}:\d{2})
- Group 1: 2 digits, :
, 2 digits~Flight-\d+
- a ~Flight-
substring and then 1+ digits\s*
- 0+ whitespaces(\d{2}:\d{2})
- Group 2: 2 digits, :
, 2 digitsJS usage:
var rx = /(\d{2}:\d{2})~Flight-\d+\s*(\d{2}:\d{2})/g;
var s = "Flight-1 08:30~Flight-1 10:45|Flight-2 15:15~Flight-2 17:30";
var m, res = [];
while (m = rx.exec(s)) {
res.push(m[1] + "-" + m[2]);
}
console.log(res);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments