user3259983 user3259983 - 1 month ago 9
Javascript Question

Regular Expression with start of string (^) cannot match Array.toString() in IE8

I am doing a regular expression check on the pattern

function Object() {}
and I use the statement

Array.toString().match(/^function\s+([^\(]+)/)


This statement works in modern browsers and returns
["function Array", "Array"]


But in Internet Explorer 8, the above statement always return
null
. After some try and error I found that the problem occurs at the
^
symbol. When I remove it to
Array.toString().match(/function\s+([^\(]+)/)
, the result becomes correct.

But the latter regular expression is not logically correct because it does not guarantee the
function
keyword starts from the beginning, thus possible giving some false positive.

I would like to know is there work around or I have missed something? Thank you.

Update:

After @nicael suggestion, I test a bunch of regular expressions and found an interesting result

Correct
means it returns
["function Array", "Array"]



  1. Matching the string instead of
    Array.toString()
    -> Correct



'
function Array() { [native code] } '.match(/^function\s+([^\(]+)/)



  1. Replace
    ^
    with
    .{1,10}
    ->
    null



Array.toString().match(/.{1,10}function\s+([^\(]+)/)



  1. Replace
    ^
    with
    .+
    ->
    null



Array.toString().match(/.+function\s+([^\(]+)/)



  1. Replace
    ^
    with
    .{0}
    -> Correct



Array.toString().match(/.{0}function\s+([^\(]+)/)


The most interesting result is that with
.{0}
, it works. But it is actually matching nothing. I am thinking if the
Array.toString()
actually outputs something before the
function...
string but using
document.write()
cannot show it but still it does not explain how
.{0}
and
^
differs (only in IE8)

Final Update:

It turns out that the problem is that
Array.toString
does not return the function string in one-line but multiple lines. So the correct regular expression to work across browsers will be
Array.toString().match(/[\r\n]?function\s+([^\(]+)/)

Answer

If you type Array.toString() in IE8 console, you can see that the output is not the string

`function Array() { [native code] }`

Instead, the output is

`
function Array() {
    [native code]
}
`

That is, there is a newline before function. That's why your regex doesn't match.