This splits the string as wanted but doesn't keep the seperator:
"200 g Joghurt".split(/[0-9]?\s?[–|-]?\s?[0-9]+\s?g{0,1}\b/)
["", " Joghurt"]
I have cases like this
- 100-200g
- 1g
- 240 - 1500 g
This thread suggest to use a positive look ahead. Javascript and regex: split string and keep the separator
But if I put it in it splits to much:
"200 g Joghurt".split(/(?=[0-9]?\s?[–|-]?\s?[0-9]+\s?g{0,1}\b)/)
["2", "0", "0 g Joghurt"]
Question: How to split that string above (numbers can be any number, Joghurt can be any word) after the numbers and g. e.g.
["200-400g", "joghurt"]
EDIT: There are cases where I don't have the g e.g.
- 1 song
- song
- michael jackson song
So just matching with the g does not work. The cases I put in the examples are the cases with an g. And the g is always combined with one number or a range of numbers. Sorry about the confusion. I want to split recipe ingredients into the ingredient and the amount. The g is gram, maybe that makes the use case more clear.
EDIT 2: I also modified it a bit, the regex basically works as you can see in this example: https://regex101.com/r/rL7hY9/1 But it does not split it in a whole block. I also have this problem with my other regex cases, the match on regex101 is the whole group. But .split() does not split it in one part (with the positive lookahead).
200 g Joghurtbecomes["200-400g","joghurt"]?