slayeroffice - web experiments gone horribly awry

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.

Wouldn't you consider this an instance where the spec is dumb and the Mozilla guys did us a favor?
Posted by Marco Rogers on May 14, 2008 @ 12:00 am
Well, no - it seems to me that a method should always return the same data type regardless. I think we've just become accustomed to how javascript is so loosely typed that it doesn't occur to us that this sort of thing isn't right. :)
Posted by steve on May 14, 2008 @ 8:02 am
I think it is one of those times when both are wrong and something new needs to be done in order to solve this problem, please let us know what you come up with because you have us scratching our heads over here.
Posted by Janet on May 29, 2008 @ 4:31 am
You've got it easy until you try loading JS through AJAX :|
Posted by David on June 20, 2008 @ 9:17 pm
I don't know which is right, but, I would 'expect' to see a null value returned, returning an empty array just does not make sense to me... it just makes it more difficult to test for.
Posted by Joe Freeline on July 14, 2008 @ 11:49 am
I agree with the above poster, I would expect to see a null value returned.
Posted by kraig aka font on September 11, 2008 @ 4:56 am
it seems to me js code ??
Posted by emre on May 18, 2009 @ 4:31 pm

Comments have been closed for this post.