How to get first character of string?

后端 未结 17 2278
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 09:43

I have a string, and I need to get its first character.

var x = \'somestring\';
alert(x[0]); //in ie7 returns undefined

How can I fix my co

相关标签:
17条回答
  • 2020-11-27 10:28

    It's been 10 years yet no answer mentioned RegExp.

    var x = 'somestring';
    console.log(x.match(/./)[0]);

    0 讨论(0)
  • 2020-11-27 10:31

    Example of all method

    First : string.charAt(index)

    Return the caract at the index index

    var str = "Stack overflow";
    
    console.log(str.charAt(0));

    Second : string.substring(start,length);

    Return the substring in the string who start at the index start and stop after the length length

    Here you only want the first caract so : start = 0 and length = 1

    var str = "Stack overflow";
    
    console.log(str.substring(0,1));

    Alternative : string[index]

    A string is an array of caract. So you can get the first caract like the first cell of an array.

    Return the caract at the index index of the string

    var str = "Stack overflow";
    
    console.log(str[0]);

    0 讨论(0)
  • 2020-11-27 10:32

    x.substring(0,1)

    Details

    substring(start, end) extracts the characters from a string, between the 2 indices "start" and "end", not including "end" itself.

    Special notes

    • If "start" is greater than "end", this method will swap the two arguments, meaning str.substring(1, 4) == str.substring(4, 1).
    • If either "start" or "end" is less than 0, it is treated as if it were 0.
    0 讨论(0)
  • 2020-11-27 10:33

    you can use in this way:

    'Hello Mr Been'.split(' ').map( item => item.toUpperCase().substring(0, 1)).join(' ');
    
    0 讨论(0)
  • 2020-11-27 10:35

    in Nodejs you can use Buffer :

    let str = "hello world"
    let buffer = Buffer.alloc(2, str) // replace 2 by 1 for the first char
    console.log(buffer.toString('utf-8')) // display he
    console.log(buffer.toString('utf-8').length) // display 2
    
    0 讨论(0)
  • 2020-11-27 10:38
    var str="stack overflow";
    
    firstChar  = str.charAt(0);
    
    secondChar = str.charAt(1);
    

    Tested in IE6+, FF, Chrome, safari.

    0 讨论(0)
提交回复
热议问题