05.12.2008 - Does it .match?
I've been doing some work in AS3 of late and stumbled onto a bit of a gotcha last week that I thought I'd share since it caused me about 15 minutes of frustration.
The gotcha pertains to a significant difference in how Javascript and AS3 handle the match method of the String object when the global flag is passed. Consider the following Javascript snippet:
var r = /[a-z]/g
var s = "abc";
var x = s.match(r);
This will return an Array with values "a,b,c" in both Javascript and in its AS3 equivalent.
Now, consider this code, replacing the value of s
with something that will not match:
var r = /[a-z]/g
var s = "123";
var x = s.match(r);
In Javascript, this will return null
, but AS3 will return a zero length Array. Which means that this...
if(s.match(r)) {
// do stuff...
}
..would always be true in AS3, but false in Javascript. I spent about 10 minutes thinking there was something wrong with my regular expression, and another five thinking there was something wrong with AS3's regexp engine before I realized what was happening.
So who has it right? According to the ECMA 262 spec, AS3 does (see page 101-102). Of course, Mozilla's documentation claims that it will return an Array as well with no mention of null
on that page, while Microsoft's JScript documentation admits it will return null
if no match is found.
Good times.
Posted by Marco Rogers on May 14, 2008 @ 12:00 am
Posted by steve on May 14, 2008 @ 8:02 am
Posted by Janet on May 29, 2008 @ 4:31 am
Posted by David on June 20, 2008 @ 9:17 pm
Posted by Joe Freeline on July 14, 2008 @ 11:49 am
Posted by kraig aka font on September 11, 2008 @ 4:56 am
Comments have been closed for this post.