views:

38

answers:

3

Hi,

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?

+8  A: 

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
+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
Thanks, this works a treat in IE!
Adam Witko
+1  A: 

You can use .substr().

var firstChar = text.substr(0,1);
patrick dw
I'd use this as it's the most cross-browser compatible.
Paulo Santos
A: 

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

Litso