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

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

如何修复我的代码?


当前回答

已经12年了,只有一个开发人员提到了regexp,但它是一种更简单的方法:

const str = 'string';

str.match(/\w/); // >> s

它将返回给定字符串中的第一个字符类单词。

其他回答

所有方法示例

第一个:string.charAt(index)

返回索引index处的caract

var str = “堆栈溢出”; console.log(str.charAt(0));

第二个:string.substring(start,length);

返回字符串中从索引start开始并在长度length之后停止的子字符串

这里你只需要第一个caract: start = 0 and length = 1

var str = “堆栈溢出”; console.log(str.substring(0,1));

string[index]

字符串是一个caract数组。所以你可以得到第一个caract就像数组的第一个单元格。

返回字符串的下标处的caract

var str = “堆栈溢出”; console.log(str[0]);

X.s ubstring (0, 1)

细节

Substring (start, end)从字符串中提取出两个索引"start"和"end"之间的字符,不包括"end"本身。

特别指出

如果"start"大于"end",该方法将交换两个参数,即str.substring(1,4) == str.substring(4,1)。 如果“start”或“end”小于0,则将其视为0。

已经12年了,只有一个开发人员提到了regexp,但它是一种更简单的方法:

const str = 'string';

str.match(/\w/); // >> s

它将返回给定字符串中的第一个字符类单词。

在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)

如果charAt()有父道具,则不工作 前女友parent.child.chartAt (0) 使用parent.child。片(0,1)