skip to Main Content

Does anyone has an explanation why this regular expression test returns false in the browser’s console?

enter image description here

In the screenshot above, I create a regex (first line), then test it against a string that should match, but,oddly enough, the test returns false (second line).

What’s strange is that the test returns "true" as long as I don’t press "Enter" (third line).

Regards,

Cyrille

2

Answers


  1. JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g., /foo/g or /foo/y). They store a lastIndex from the previous match. Using this internally, test() can be used to iterate over multiple matches in a string of text (with capture groups).

    Source from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

    Login or Signup to reply.
  2. The behavior you’re observing is due to the way the global (g) flag affects the regular expression’s lastIndex property in JavaScript.

    When you create a regular expression with the global flag (g), the RegExp object keeps track of the position of the last match using the lastIndex property. This property allows the regular expression to resume searching from where the last match ended, rather than starting over from the beginning of the string.

    To avoid this behavior, you can either remove the global flag

    const r = new RegExp('test');
    
    console.log(r.test('this is a test')); // true
    

    alternative solution if you don’t need it or manually reset lastIndex to 0 before each test:

    const r = new RegExp('test', 'g');
    
    r.lastIndex = 0;
    console.log(r.test('this is a test')); // true
    
    r.lastIndex = 0;
    console.log(r.test('this is a test')); // true
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search