Reputation: 193
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
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
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