9

I have a variable:

var text = "hello";

I want to get the 0 positioned character, so:

var firstChar = text[0];

Simple. In firefox and chrome this works. In IE however i always get back 'undefined'

Any ideas why this might be happening in IE?

Garis M Suero
  • 7,974
  • 7
  • 45
  • 68
adamwtiko
  • 2,865
  • 8
  • 39
  • 47
  • 3
    From now, learn that everything that works in `good` browsers doesn't work in `IE`. I think MS people wanted to code an extra dimension aside the current web development context. – Garis M Suero Sep 08 '10 at 14:32
  • Addenda: works fine in IE8 (as I write this), and in IE7 instead of throwing an error returns something that is parsedInt'ed as NaN instead of exploding. Tracking this problem sure took much longer than it should... – ANeves Jan 07 '11 at 18:37

3 Answers3

17

Strings aren't accessible like arrays in IE (prior to IE9). Instead you can use charAt, which is available cross-browser:

var text = "hello";
var firstChar = text.charAt(0);
// firstChar will be 'h'
Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
  • 1
    +1 for *charAt()*. FWIW, IE8 in standards mode and IE9 support array-style referencing of characters in strings just like Chrome and Firefox. – Andy E Sep 08 '10 at 14:36
1

You can use .substr().

var firstChar = text.substr(0,1);
user113716
  • 318,772
  • 63
  • 451
  • 440
0

I'm not sure why that doesn't work, but you could try using substr()

Stephan Muller
  • 27,018
  • 16
  • 85
  • 126