Search code examples
javascriptsplit

Split with multiple delimiters, and with multiple characters in each delimiter


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 !


Solution

  • Use a regex that will accept [space]-/[space]

    const hours = '13:00 - 17:00 / 20:00 - 02:00' 
    const splitted = hours.split(/\s[-\/]\s/);
    
    console.log(splitted)