1

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

1 Answer 1

2

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));
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.