skip to Main Content

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


  1. 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)
    Login or Signup to reply.
  2. I would use a match() approach here:

    var hours = '13:00 - 17:00 / 20:00 - 02:00';
    var times = hours.match(/d{1,2}:d{2}/g);
    console.log(times);

    This approach avoids the messiness in trying to articulate the required delimiters for splitting.

    Login or Signup to reply.
  3. The regular expression / - | / / matches ‘ – ‘ and ‘ / ‘, which are the patterns separating the times in string.

    const hours = '13:00 - 17:00 / 20:00 - 02:00';
    const hoursArray = hours.split(/ - | / /);
    console.log(hoursArray);
    Login or Signup to reply.
  4. const hours = '13:00 - 17:00 / 20:00 - 02:00';
    const matches=hours.match(/d{2}:d{2}/g);
    console.log(matches);

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search