How to get first character of string?

后端 未结 17 2277
被撕碎了的回忆
被撕碎了的回忆 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:15
    var x = "somestring"
    alert(x.charAt(0));
    

    The charAt() method allows you to specify the position of the character you want.

    What you were trying to do is get the character at the position of an array "x", which is not defined as X is not an array.

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

    const x = 'some string';
    console.log(x.substring(0, 1));

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

    What you want is charAt.

    var x = 'some string';
    alert(x.charAt(0)); // alerts 's'
    
    0 讨论(0)
  • 2020-11-27 10:19

    You can even use slice to cut-off all other characters:

    x.slice(0, 1);
    
    0 讨论(0)
  • 2020-11-27 10:20

    In JavaScript you can do this:

    const x = 'some string';
    console.log(x.substring(0, 1));

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

    You can use any of these.

    There is a little difference between all of these So be careful while using it in conditional statement.

    var string = "hello world";
    console.log(string.slice(0,1));     //o/p:- h
    console.log(string.charAt(0));      //o/p:- h
    console.log(string.substring(0,1)); //o/p:- h
    console.log(string.substr(0,1));    //o/p:- h
    console.log(string[0]);             //o/p:- h
    
    
    var string = "";
    console.log(string.slice(0,1));     //o/p:- (an empty string)
    console.log(string.charAt(0));      //o/p:- (an empty string)
    console.log(string.substring(0,1)); //o/p:- (an empty string)
    console.log(string.substr(0,1));    //o/p:- (an empty string)
    console.log(string[0]);             //o/p:- undefined
    
    0 讨论(0)
提交回复
热议问题