-2

I am trying to parse a string into:

  • Remove initial "lunch" word
  • Split the rest into days of week and their associated food item

The input comes in just as a string in this format:

var s = 'lunch monday: chicken and waffles, tuesday: mac and cheese, wednesday: salad';

And my goal is to split into:

[monday, chicken and waffles, tuesday, mac and cheese, wednesday, salad]

I am using s = s.split(' ').splice(1, s.length-1).join(' ').split(':');

Which gets me:

["monday", " chicken and waffles, tuesday", " mac and cheese, wednesday", " salad"]

Obviously it's splitting on the : only, keeping the , there. I've tried using regex split(":|\\,"); to split on : OR , but this does not work.

Any thoughts?

user3871
  • 12,432
  • 33
  • 128
  • 268

3 Answers3

1

If you want to split on both of those, you just need to adjust your Regular Expression a bit :

// Notice the 'g' flag which will match all instances of either character
input.split(/[:,]/g);

You could combine all of these to get what you are looking for via thereplace() and split() functions:

// The initial replace will trim any leading "lunch " and the split will handle the rest
var output = input.replace(/^lunch /,'').split(/[:,]/g); 

Example

var input = 'lunch monday: chicken and waffles, tuesday: mac and cheese, wednesday: salad';
var output = input.replace(/^lunch /,'')
                  .split(/[:,]/g)
                  .filter(function(x){ return x.length > 0;});
alert(output);
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
0

I'm not sure if understand your goal. But is this

 var string = 'lunch monday: chicken and waffles, tuesday: mac and cheese, wednesday: salad';

var splittedString = string.split(/:|,/);

splittedString.forEach(function(e){
    document.write(e + "<br>")
});

what you are looking for?

Simon Schüpbach
  • 2,625
  • 2
  • 13
  • 26
0

Here is a solution with replace() and split()

var s = 'lunch monday: chicken and waffles, tuesday: mac and cheese, wednesday: salad';

s = s.replace('lunch ', '');
s = s.replace(/:(\ )/g, ',');
s = s.split(',');
console.log(s);

Output:

["monday", "chicken and waffles", " tuesday", "mac and cheese", " wednesday", "salad"]

Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60