G spot for Regex

Everyone uses regular expressions. Sometimes they are just the simplest way to check or extract something from the text. Regular expressions in JS can be modified with flags. Two are simple: ‘i’ stands for ‘case insensitive’, ‘m’ for ‘multiline’. There is one inconspicuous flag though that is called ‘g’. In spec, it is explained simply as ‘global match’. But what does it really mean?

Actually, it means that you shouldn’t use it unless you need it. Consider this code, for example:

var rx = new RegExp("a", "ig");

function check_match(s) {
    var match = rx.exec(s);
    return !!(match && match.length > 0);

And now we call it:

var s = "aba";
>> true
>> true
>> false

So, how come the result is different on the third time?
Well, actually, the ‘g’ flag helps find consecutive matches. It remembers the last position and starts from there next time it commences a search.

This useful feature might lead to unexpected bugs, so it’s better to know how it works!


About Maryna Cherniavska

I have productively spent 10+ years in IT industry, designing, developing, building and deploying desktop and web applications, designing database structures and otherwise proving that females have a place among software developers. And this is a good place.
This entry was posted in javascript and tagged . Bookmark the permalink.

One Response to G spot for Regex

  1. Pingback: G spot for Regex | Dinesh Ram Kali.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s