0

Can someone help check this snippet? I'm just looping on array but the last item return false or null even its matches the pattern.

let texts = ["Invoice_001_1", "Invoice_001_2"];
var regTest = /(([a-zA-Z 0-9]+)_([0-9]+)_([0-9]+)$|[a-zA-Z ]+_([0-9]+)$)/gi;

for(var x=0; x<texts.length; x++) {
    console.log(texts[x]);
    var matchReg = regTest.exec(texts[x]);
    console.log(matchReg);
}

JSfiddle Demo

bumbumpaw
  • 2,522
  • 1
  • 24
  • 54
  • to put it simply: never ever use `regex.exec` in javascript. It's broken. Use `string.match` instead. – gog Nov 21 '22 at 16:45

1 Answers1

1

The issue is that when using /g, js has a little gotcha, in that it tells the regexp to keep the index of the last match.The fix is to manually reset the index:

let texts = ["Invoice_001_1", "Invoice_001_2"];
var regTest = /(([a-zA-Z 0-9]+)_([0-9]+)_([0-9]+)$|[a-zA-Z ]+_([0-9]+)$)/gi;

for(var x=0; x<texts.length; x++) {
        console.log(texts[x]);
        var matchReg = regTest.exec(texts[x]);
    console.log(matchReg);
    regTest.lastIndex = 0;
}
dave
  • 62,300
  • 5
  • 72
  • 93