I would like to split the following string
const hours = '13:00 - 17:00 / 20:00 - 02:00'
into this array
['13:00', '17:00', '20:00', '02:00']
where there are no spaces, no ‘/’ and no ‘-‘.
I tried with this syntax :
hours.split(' - | / ')
but it doesn’t work. And I don’t find the good syntax using regex ;(
I would like to do it in one line, and not like that :
hours
.replaceAll(' ','')
.replace('/','-')
.split('-');
Can somebody help ? Thanks !
4
Answers
Use a regex that will accept
[space]-/[space]
I would use a
match()
approach here:This approach avoids the messiness in trying to articulate the required delimiters for splitting.
The regular expression
/ - | / /
matches ‘ – ‘ and ‘ / ‘, which are the patterns separating the times in string.Looks like you are trying to find the time format regardless of spaces or delimiters, suggesting to use match regex here
d{2} >> will matche exactly 2 digits
: >>literal colon
d{2} >> once more