Javascript strings - getting the char at a certain point

前端 未结 3 1248
梦谈多话
梦谈多话 2021-01-12 00:01

I have a variable:

var text = \"hello\";

I want to get the 0 positioned character, so:

var firstChar = text[0];


        
相关标签:
3条回答
  • 2021-01-12 00:32

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

    0 讨论(0)
  • 2021-01-12 00:34

    You can use .substr().

    var firstChar = text.substr(0,1);
    
    0 讨论(0)
  • 2021-01-12 00:41

    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'
    
    0 讨论(0)
提交回复
热议问题