Beware of the g flag when using regular expressions in javascript …

The following experience with regular expressions in Javascript has cost me a few hours of my life, thus it is probably worth to share it. This is bascially about the “g” flag ( described for instance in this tutorial here ): The “g” flag is the “global search flag” and is supposed to search for a pattern throughout the entire string given. Nevertheless, apparently this creates the situation that you can use a regular expression only once in your code. Look at this code sample:

  1:   regex = /Hello/g;
  2:   text = "Hello World!";
  3:   document.getElementById("my_output").innerHTML = "<p>Testing string \"" + text + "\" with regex <strong>" + regex + "</strong> : " + regex.test(text) + "</p>";
  4:   document.getElementById("my_output").innerHTML += "<p>Testing string \"" + text + "\" with regex <strong>" + regex + "</strong> : " + regex.test(text) + "</p><hr>"; 

What would you think is the output from the last two statements ? “True” and “true”, you think, since it looks like the test should be positive and those two statements are exactly the same ? If this is your answer then I can tell you it has been my expectation as well. Nevertheless: the answer is wrong. The output will be “true” in the first case, but “false” in the second case. Somehow the regular expression seems to work only once.

You can test it out with my little sample script here ( just click on the “Test…” button ).

When omitting the “g” flag you get a “true” in both cases.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: