I would like to split the string into JSON. Below is some example:
Mon, Fri 2:30 pm - 8 pm / Tues 15 am - 2 pm / Weds 1:15 pm - 3:15 am /....
Mon, Weds - Thurs, Sat 7:15 pm - 3:30 am / Tues 4:45 pm - 5 pm / Fri 8:25 am - 9:30 pm / ...
Mon, Weds - Sun 7:15 pm - 3:30 am
Mon - Sun 7:15 pm - 3:30 am
I hope I can get the JSON from each line:
[
{
day: Mon,
openning_time: 7:15 pm
closing_time: 3:30 am
},
....
]
I had tried many methods but still cannot make it. Hope can get some idea
I'd suggest using String.split() to split each input string into fields.
Once this is complete we'll use a regular expression to parse each field into day, opening time and closing time using String.match().
We'd also create a splitDays() function to turn a day range like Mon, Weds - Thurs into an array of days like [Mon,Weds,Thurs], this will allow us to create the final result.
function splitDays(days) {
return days.split(',').flatMap(splitDayRange);
}
function splitDayRange(range) {
const days = ['Mon', 'Tues', 'Weds', 'Thurs', 'Fri', 'Sat', 'Sun'];
const [startIndex, endIndex] = range.trim().split(/\s*\-\s*/).map(day => days.findIndex(d => d === day));
return days.filter((day, idx, arr) => {
return (idx >= startIndex) && (idx <= (endIndex || startIndex));
});
}
function parseInput(input) {
const parseRegEx = /([a-z\s\,\-]*)(\d+:?\d* (?:am|pm))\s*\-\s*(\d+:?\d*\s*(am|pm))/i
return input.split(/\s*\/\s*/).flatMap(field => {
const [, days, opening_time, closing_time ] = field.match(parseRegEx);
return splitDays(days).map(day => {
return { day, opening_time, closing_time };
})
});
}
let inputs = [
'Mon, Fri 2:30 pm - 8 pm / Tues 15 am - 2 pm / Weds 1:15 pm - 3:15 am',
'Mon, Weds - Thurs, Sat 7:15 pm - 3:30 am / Tues 4:45 pm - 5 pm / Fri 8:25 am - 9:30 pm',
'Mon, Weds - Sun 7:15 pm - 3:30 am',
'Mon - Sun 7:15 pm - 3:30 am'
]
for(let input of inputs) {
console.log('Input:');
console.log(input);
console.log('Output:');
console.log(parseInput(input));
}
.as-console-wrapper { max-height: 100% !important; }
Probably this is not a best performance solution but you can get the idea. The last part is missing because I'm not sure of the day notation so I leave that to you. Basically what you have to implement is another flatmap that splits the day string in an array of days
const stringToParse =
`Mon, Fri 2:30 pm - 8 pm / Tues 15 am - 2 pm / Weds 1:15 pm - 3:15 am
Mon, Weds - Thurs, Sat 7:15 pm - 3:30 am / Tues 4:45 pm - 5 pm / Fri 8:25 am - 9:30 pm
Mon, Weds - Sun 7:15 pm - 3:30 am
Mon - Sun 7:15 pm - 3:30 am`;
const daysArray = ['Mon', 'Tues', 'Weds', 'Thurs', 'Fri', 'Sat', 'Sun']
const json = stringToParse.split('\n')
.flatMap(line => line.split('/').map(s => s.trim()))
.map(s => {
const [closingType, closing, _,openingType, opening, ...days] = s.split(' ').reverse()
return {
days: days.reverse().join(' '),
openning_time: `${opening} ${openingType}`,
closing_time: `${closing} ${closingType}`
}
})
console.log(json)