Javascript strings - getting the char at a certain point

☆樱花仙子☆ 提交于 2019-12-04 01:03:31

问题


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?


回答1:


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'



回答2:


You can use .substr().

var firstChar = text.substr(0,1);



回答3:


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



来源:https://stackoverflow.com/questions/3668693/javascript-strings-getting-the-char-at-a-certain-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!