Portable JavaScript: String indexing

In JavaScript, Web development on June 15, 2008 by Matt Giuca

A short community service announcement. I recently got burned on a JavaScript project which, as usual, wasn’t working in Internet Explorer. I decided to track down one of the issues which simply caused an “error on page” message in IE.

It turns out that string indexing (such as str[index]) doesn’t work in IE. You need to do this:


The technical reason for this is that IE doesn’t implement JavaScript, it implements JScript. Both are derivatives of ECMAScript. The str[index] feature is a feature of JavaScript alone, not ECMAScript or JScript.

(I think Microsoft were forced to call it JScript for legal reasons, but it does give them the convenient excuse “hey, this isn’t JavaScript, it’s JScript”).

From Mozilla’s reference:

The second way (treating the string as an array) is not part of the ECMAScript; it’s a JavaScript feature.

So there you go – charAt from now on!

(Another similar tip: Don’t leave a trailing comma at the end of an object literal – it works in JavaScript but not in ECMAScript, or IE).

Now if you’ll excuse me, I’m off to grep for ‘[‘. 😦

Update: The square-bracket indexing feature is included in ECMAScript 5 so should become a standard feature. From Mozilla’s reference:

Array-like character access (the second way above) is not part of ECMAScript 3. It is a JavaScript and ECMAScript 5 feature.

Also, it appears to be supported in Internet Explorer 8 and above (although I haven’t tested it). Thanks to Jean-Marc Desperrier and Chris Donnelly (in the comments) for pointing these out.


4 Responses to “Portable JavaScript: String indexing”

  1. IE8 and up appear to support it; it’s only IE6 and 7 that don’t.

    (Not sure what IE8’s IE7 compatibility mode does, but presumably it wouldn’t.)

  2. Your mozilla link is outdated. The up-to-date one is this one :

    It now says about this array-like access : “not part of ECMAScript 3. It is a JavaScript and ECMAScript 5 feature”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: