Regex.test() function of javascript returns alternate results

Recently faced one strange issue. Regex.test() function of javascript was returning alternate results. I thought I made some mistake in writing the logic. But later when I debugged, I found that javascript function itself was behaving strangely. I googled it and found a new thing which I wasn’t knowing. So posting here for reference. Thanks to stack overflow 🙂

This is the RegExp which I was using [ /^([\+](?:\d{1,3})[-]\d{10})$/gi ]. Its a Global RegExp (contains g).

In JavaScript, Global RegExp have state which is used for finding multiple matches. We call either exec, test etc. methods to find match. First time execution of one of these methods give first match. Call them again and you get the next match, and so on until you get no match and it resets to the start of the next string.

There are two ways to change this behaviour (if you are dealing with single match):
(1) You can write regex.lastIndex= 0 to reset the state of the RegExp.
(2) Remove (g) from your RegExp.

[Reference: http://stackoverflow.com/questions/2630418/javascript-regex-returning-true-then-false-then-true-etc]

Unknown's avatar

Author: Makarand Thengdi

Director of Engineering, DevOps, and Releases at LeadSquared, with over a decade of experience in leading engineering and DevOps transformations for high-growth companies. Passionate about optimizing software delivery pipelines, cloud infrastructure, and security compliance. In this blog, I share my learnings and insights on DevOps, cloud technologies, and modern software engineering, reflecting my journey from code to cloud.

Have something to say ?

This site uses Akismet to reduce spam. Learn how your comment data is processed.