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.