Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript strings - getting the char at a certain point

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?

like image 732
adamwtiko Avatar asked Sep 08 '10 14:09

adamwtiko


2 Answers

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'
like image 97
Daniel Vandersluis Avatar answered Nov 19 '22 01:11

Daniel Vandersluis


You can use .substr().

var firstChar = text.substr(0,1);
like image 25
user113716 Avatar answered Nov 19 '22 00:11

user113716