views:

39

answers:

1

This simple regex matching returns a string instead of an object on every browser but the latest firefox...

        text = "language. Filename: My Old School Yard.avi. File description: File size: 701.54 MB. View on Megavideo. Enter this, here:"
    name = text.match(/(Filename:)(.*) File /);
    alert(typeof(name));

as far as i know this the match function is suppose to return an object (Array). Has anyone come across this issue?

+1  A: 

The RegExp match method does return an array, but arrays in JavaScript are simply objects that inherit from Array.prototype, e.g.:

var array = "foo".match(/foo/); // or [];,  or new Array();

typeof array; // "object"
array instanceof Array; // true
Object.prototype.toString.call(array); // "[object Array]"

The typeof operator will return "object" because it can't distinguish between an ordinary object and an array.

In the second line I use the instanceof operator to prove that the object is actually an array, but this operator has known issues when working in cross-frame environments.

In the third line I use the Object.prototype.toString method, which returns a string that contains the [[Class]] internal property, this property is a value that indicates the kind of the object, a much safer way to detect if an object is an array or not.

CMS