0

I have a problem when I run this Regex multiple times quickly in a row. If it's too fast the array returns as null. If I wait a second in between running it I don't get an error. I'm pretty sure the regex is the problem because I can log data just before without any problems.

let reg = /(\d+)d(\d+).+?\s(\d+|\d{1,3},\d{3})*?(\.\d+)*?\sgp\s(.+)/g;
let arr = reg.exec(data);

Example of data:

  • 1d8 (4) 5,000 gp gems
  • 3d6 (10) 1,000 gp gems
  • 1d4 (2) 7,500 gp art objects
  • 1dl0 (5) 2,500 gp art objects

Edit: Here is the full code. I am getting arr as null and an error at let price = ("gp" + arr[3].replace(/,/g, ''));. And data is just a single string, like "1d8 (4) 5,000 gp gems". Still have the problem after taking out the g.

async function getObjects(data) {
    if (data !== "*") {
        chrome.extension.getBackgroundPage().console.log(data);
        let reg = /(\d+)d(\d+).+?\s(\d+|\d{1,3},\d{3})*?(\.\d+)*?\sgp\s(.+)/g;
        let arr = reg.exec(data);
        chrome.extension.getBackgroundPage().console.log(arr);
        let url = chrome.runtime.getURL("objects.json");
        let price = ("gp" + arr[3].replace(/,/g, ''));
        let name = arr[5] + " " + price;
        let sum = sumRolls(arr[1], arr[2]);

        let objects = await returnJSON(url, "name", name);       
        let num = objects[0].group.length;
        let output = [];

        for(let i = 0; i < sum; i++){
            let roll = Math.floor((Math.random() * num));
            output.push(objects[0].group[roll].desc);
        };
        return output;
    };
};
bigbucky
  • 407
  • 6
  • 20
  • `Example of data` What exactly is that, a multiline string or what? Works fine for me, not many steps at all https://regex101.com/r/Uaj9qT/1 can you post your full code? – CertainPerformance Nov 29 '18 at 01:03
  • Remove the `/g` flag. – melpomene Nov 29 '18 at 01:04
  • It's hard to tell without a [mcve], but this is probably a duplicate of [Why does a RegExp with global flag give wrong results?](https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results). – melpomene Nov 29 '18 at 01:06

0 Answers0