Question : Strange JavaScript Regex Behavior in Firefox and Opera After KeyUp Event

Create a page containing the attached code snippet and view the page in Firefox (or Opera, they both do this, but not IE or Safari). Type "8" (or any other digit) followed by a single letter, say "e", repeated several times. Each time you hit the "e" key, the result of the RegExp test that gets printed back into the second text box will alternate between true/false. WHY???

This simplified test case demonstrates what I think is a bug, but one that appears in current versions of two major browsers. The regular expression is testing for the existence of a digit. If I put one digit at the start of the test string, no quantity of subsequent characters should alter the result. This is one example of many - I have found that many regex patterns return unexpected results when used to test the value of a text box following the KEYUP event.

If you place a breakpoint on the return line and copy the return expression into the Firebug console it will always return true, even though executing that same line immediately after returns false.

The answer I am looking for is either an explanation of this behaviour that would convince me it isn't a bug, or a practical workaround that makes the second box always return true. Meanwhile I've reported it on BugZilla.
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

	
		
		
		
	

Open in New Window Select All

Answer : Strange JavaScript Regex Behavior in Firefox and Opera After KeyUp Event

It rang a bell... Here's what's happening: the lastIndex property is not being reset. You can see that when you type a larger number, in which case "true" and "false" is not just alternated, it is "twice true, one false" for 2 digits plus one or more letters, and "thrice true, one false" for three digits plus one or more letters.

According to a blog post, it is the third most reported "bug" for Firefox:

Another historically problematic issue has been the fact that, according to ES3, regex literals cause only one object to be created at runtime for a script or function. This issue exhibits itself most frequently as regex literals which use the /g modifier not having their lastIndex property reset in some cases where most developers would expect it. Fortunately, this is already planned to be fixed in ES4. The fact that it has been the third most duplicated Firefox bug report undoubtedly had something to do with this decision.


In general, I would say, this is "not a bug". Actually: IE has it wrong here and Opera and Firefox do it well. And yes, that it is far from intuitive in this case...

I'm sure you have found a workaround: not using the "g" modifier, or resetting lastIndex by hand. Also, you could use $ and ^ to aid in your match.
Random Solutions  
 
programming4us programming4us