How can I split this string
42% recycled nylon 41% nylon 17% elastane
into
42%
recycled nylon
41%
nylon
17%
elastane
(with regex?) ?
I have already tried and used .split(/s(?=d)/) but this turns the string into this :
42% recycled nylon
41% nylon
17% elastane
Thank you
3
Answers
You’re already using positive-lookahead; you can combine with positive-lookbehind:
For a break down, see this in regex101
You can use the following regex:
/(d+%)/g
However, that results in the output array having one or more empty strings. We can get rid of those using a neat trick with
.filter(Boolean)
. You can google the explanation of what exactly it does.But there’s a second problem. The white spaces around the strings are not removed by the regex, so you should map the array and use
.trim()
on the elements. So, your final script should be something like this:Since normal text and numbers with percentage are always separated with space, we can simply split the string by space and, with a combination of
.map()
and.filter()
glue neighbors that are not numbers with percentages: