Search code examples
javascriptregexnegative-lookbehind

Regex match comma when condition is met


Currently, I have a problem with matching comma in some conditions.

for example

<product_11,product_12>=5,product_1,product_2,product_3=1,product_9=3,<product_5,product_6>=10,product_11,product_12,product_13,product_14=20

I don't want to match that comma when there is =\d+ and inside <>, so, in this case, the comma that I want to match is only from product_1,product_2,product_3 and product_11,product_12,product_13,product_14=20.

Actually, I have already done the code and it works fine, but as I knew the code is only for ECMAScript 2018 compliant environments and it doesn't support browsers like Mozilla, ie, etc

Here is my regex code.

(?<!\s*[=]\s*\d+)\,\s?(?![^\<]*\>)

https://regex101.com/r/lS5tT3/231

Are there any other options to match the comma that I expect?

I want to replace the matching comma to /

so the output will be

<product_11,product_12>=5,product_1/product_2/product_3=1,product_9=3,<product_5,product_6>=10,product_11/product_12/product_13/product_14=20

Solution

  • You could make use of an alternation and a callback function for replace.

    In the alternation you can match what you want and what you don't want. In the replace function you can check if the match is a single comma and replace that with a forward slash.

    <[^<>]+>|=\d+,|,
    

    Regex demo

    For example:

    let pattern = /<[^<>]+>|=\d+,|,/g;
    let str = `<product_11,product_12>=5,product_1,product_2,product_3=1,product_9=3,<product_5,product_6>=10,product_11,product_12,product_13,product_14=20`;
    str = str.replace(pattern, function($m) {
      return $m === "," ? '/' : $m;
    });
    console.log(str);