Jérôme
Jérôme

Reputation: 56

Typescript nodejs - Regex pattern is not working inside a variable

I'm trying to test a little regex pattern on a string array. When I use the pattern directly with test function, it works correctly. But when I use the pattern as a constant variable, it doesn't work anymore.

Can someone explain what's wrong with my code ? Or how can I correct this ?

Thanks :)

const strArray = ['(', 'ATT1', 'VARCHAR2', ')'];

const testingWord = (pString: string) => /^[^;() ]+$/g.test(pString);
strArray.map((word) => {
   console.log(word, testingWord(word));
});
// RESULT
// (        false
// ATT1     true
// VARCHAR2 true
// )        false

const PATTERN_WORD = /^[^;() ]+$/g;
const test = (pString: string) => PATTERN_WORD.test(pString);
strArray.map((word) => {
   console.log(word, testingWord(word));
});

// RESULT
// (        false
// ATT1     true
// VARCHAR2 false  <-- this should be true
// )        false

Upvotes: 1

Views: 718

Answers (1)

Gerrit0
Gerrit0

Reputation: 9182

You've just discovered why using the g flag in regexes can be problematic.

The RegExp object has a property - lastIndex. Which is set when the object is used to match (or test) a string if the y or g flags are used.

This property is used when determining where to start matching, so if it isn't 0, your regex might miss some properties.

Since you are only using this regex with .test, get rid of the g flag. It won't change the behavior of the regex.

const PATTERN_WORD = /^[^;() ]+$/; // <-- here
const test = (pString: string) => PATTERN_WORD.test(pString);
strArray.map((word) => {
   console.log(word, testingWord(word));
});

Upvotes: 2

Related Questions