我有一个字符串,我需要得到它的第一个字符。

Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined

如何修复我的代码?


当前回答

你可以用任何一个。

所有这些都有一点不同 所以在条件语句中使用时要小心。

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 console.log(string.at(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 console.log(string.at(0)); //o/p:- undefined

其他回答

对于任何字符串str = "Hello World"

str.split(' ')。map(item => item. touppercase()。substring(0,1))。加入(' ');

输出:H W

var x = "somestring"
alert(x.charAt(0));

charAt()方法允许您指定所需字符的位置。

你要做的是获取数组x的位置上的字符,它没有定义为x不是数组。

在JavaScript中,你可以这样做:

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

在Nodejs中你可以使用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

在JQuery中你可以使用: 在类中选择选项:

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

值:

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

在ID为文本值:

$("#id").val().substr(1)