JS用命令和任何数字分隔字符串

我想分隔一个字符串。

"5 tablespoons unsalted butter, melted and cooled, 1 tablespoon, softened, for brushing muffin cups, 2 cups cornmeal"

我想得到:

5 tablespoons unsalted butter, melted and cooled
1 tablespoon, softened, for brushing muffin cups
2 cups cornmeal

The pattern is: , <any number> I did some search online and tried .split(/(, \d+)/). But, it doesn't work as it give me five results. Can i get some help?

谢谢!

评论
此生不坏
此生不坏

Your (, \d+) pattern is wrapped with a capturing group and that is why split method returns both matches (comma + space + 1+ digits) and non-matches (the rest).

您可以使用

var s = "5 tablespoons unsalted butter, melted and cooled, 1 tablespoon, softened, for brushing muffin cups, 2 cups cornmeal";
console.log(s.split(/,\s*(?=\d+\b)/));

The /,\s*(?=\d+\b)/ regex matches

  • , - a comma
  • \s* - 0+ whitespaces
  • (?=\d+\b) - followed with 1+ digits and a word boundary.
点赞
评论
唱征服
唱征服

我不知道这是否可以改善,但是也许尝试一下:

const str = "5 tablespoons unsalted butter, melted and cooled, 1 tablespoon, softened, for brushing muffin cups, 2 cups cornmeal"
const result = str.split(/(, \d.*),/).map(x => x.trim()).map(x => x.replace(/,\s/, ''))

The resulting array in result is what you're asking for.

点赞
评论