How to get nth character in a string in Javascript?

后端 未结 3 1916
情书的邮戳
情书的邮戳 2020-12-05 13:12

I\'ve a string (let\'s say \"Hello World\") and I want to save the first characters of it in different variables (ex. character1 = \"H\", character2 = \"e\"...).

How

3条回答
  •  借酒劲吻你
    2020-12-05 14:08

    Let me summarize the possibilities

    given:

    var string = "HAI";
    /* and */
    var index = 1; // number ∈ [0..string.length), rounded down to integer
    
    • string.charAt(index) returns "A" (preferred)
    • string[index] returns "A" (non-standard)
    • string.substring(index, index+1) returns "A" (over-complex solution but works)
    • string.substr(index, 1) returns "A" (non-standard approach to above)

提交回复
热议问题