skip to Main Content

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


  1. You’re already using positive-lookahead; you can combine with positive-lookbehind:

    (?<=%)s|s(?=d)
    
    var s = "42% recycled nylon 41% nylon 17% elastane";
    console.log(s.split(/(?<=%)s|s(?=d)/g))

    For a break down, see this in regex101

    Login or Signup to reply.
  2. 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:

    const string = "42% recycled nylon 41% nylon 17% elastane";
    const regex = /(d+%)/g;
    const filtered = string.split(regex).filter(Boolean).map(i => i.trim());
    
    Login or Signup to reply.
  3. 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:

    let regex = /^[1-9]d*?(.d*)%$/g;
    let arr = "42.3% recycled nylon 41% nylon 17% elastane".split(" ");
    arr = arr.map(
        (item, index) => {
            if (item.match(regex)) {
                return item;
            } else {
                if ((index > 0) && (!arr[index - 1].match(regex))) {
                    return "";
                } else {
                    for (let subsequent = index + 1; (subsequent < arr.length) && (!arr[subsequent].match(regex)); subsequent++) {
                        if (!arr[subsequent].match(regex)) item += ` ${arr[subsequent]}`;
                    }
                    return item;
                }
            }
        }
    ).filter(item => item.length);
    
    console.log(arr);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search