kevinzf
kevinzf

Reputation: 193

JS seperate string by command and any number

I want to seperate a string.

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

I want to get:

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?

Thanks!

Upvotes: 1

Views: 48

Answers (2)

opr
opr

Reputation: 199

I don't know if this could be improved, but maybe try this:

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.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

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

You may use

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.

Upvotes: 1

Related Questions