2

I have an array of a sliced up sentence split, but the regex I test against each 'word' does not seem to be consistent.

function test (reg) {
  const tags = [];
  const split = ["man", "man"];

  console.log(split)
  split.forEach((word, key) => {
    console.log(key)
    if (reg.test(word)) {
      console.info('Word:', word)
      tags.push(word)
    } else {
      console.log('Not word:', word)
    }
  })
}

const pathRegex = new RegExp(/^[A-ZÀ-Ýa-zà-ý0-9_]+[^.#$?\[\]]$/g);
const pathRegex2 = new RegExp(/^[0-9a-zA-Z/-]+[^.#$?\[\]]$/g);

console.log('test 1:')
test(pathRegex)
console.log('test 2:')
test(pathRegex2)

See: https://codepen.io/TrySpace/pen/VwZNPLV?editors=1112

The output:

0
Word: man
1
Not word: man

What am I missing here?

I would expect the RegExp.test to return the same result each time.

What I did notice is when I replace reg with new RegExp(/^[A-ZÀ-Ýa-zà-ý0-9_]+[^.#$?\[\]]$/g) it will give me the expected result.

The question is why?

TrySpace
  • 2,233
  • 8
  • 35
  • 62

1 Answers1

5

Your notice is correct. The problem that regular expressions with the g modifier will keep track of the lastIndex where a match occurred. So we can say that they are stateful in that case.

You can pass a string expression and create a RegExp object in your function.

Or apply a dirty hack and reset lastIndex manually:

reg.lastIndex = 0;
CROSP
  • 4,499
  • 4
  • 38
  • 89