通过多个分隔符解析字符串

parsing a string looking at multiple delimiters

本文关键字:字符串 分隔符      更新时间:2023-09-26

我正在尝试将字符串解析为:

  • 删除首字母"午餐"
  • 将休息时间划分为一周中的几天及其相关的食物

输入以字符串的形式出现,格式如下:

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

我的目标是分裂成:

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

我正在使用s = s.split(' ').splice(1, s.length-1).join(' ').split(':');

这让我着迷:

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

很明显,它只在:上分裂,将,保留在那里。我尝试过使用regex split(":|'',");:,上进行拆分,但这不起作用。

有什么想法吗?

如果你想同时拆分这两个,你只需要稍微调整一下正则表达式:

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

您可以通过replace()split()函数将所有这些组合起来以获得您想要的内容:

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

示例

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);

这是一个使用replace()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);

输出:

【"星期一"、"鸡肉和华夫饼"、"星期二"、"mac和奶酪"、"周三"、"沙拉"】

我不确定是否理解你的目标。但是这是吗

 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>")
});

你在找什么?