How to get first character of string?

后端 未结 17 2466
被撕碎了的回忆
被撕碎了的回忆 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:38

    Looks like I am late to the party, but try the below solution which I personally found the best solution:

    var x = "testing sub string"
    alert(x[0]);
    alert(x[1]);
    

    Output should show alert with below values: "t" "e"

    0 讨论(0)
  • 2020-11-27 10:38
    var string  = "Hello World";
    console.log(charAt(0));
    

    The charAt(0) is JavaScript method, It will return value based on index, here 0 is the index for first letter.

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

    Try this as well:

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

    Using jQuery:

    var x = 'somestring';
    var y = x.substr(0, 1);
    
    0 讨论(0)
  • 2020-11-27 10:41

    in JQuery you can use: in class for Select Option:

    $('.className').each(function(){
        className.push($("option:selected",this).val().substr(1));
    });
    

    in class for text Value:

    $('.className').each(function(){
        className.push($(this).val().substr(1));
    });
    

    in ID for text Value:

    $("#id").val().substr(1)
    
    0 讨论(0)
提交回复
热议问题