我有一个字符串,我需要得到它的第一个字符。
Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined
如何修复我的代码?
我有一个字符串,我需要得到它的第一个字符。
Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined
如何修复我的代码?
当前回答
Const x = 'some string'; console.log (x。substring (0,1));
其他回答
你甚至可以使用切片切断所有其他字符:
x.slice(0, 1);
Const x = 'some string'; console.log (x。substring (0,1));
在Javascript中有很多方法可以找到字符串的第一个字符。我认为最简单的方法是string.charAt()方法。此方法以索引号作为参数并返回索引值。如果你没有给出任何参数,默认情况下它会返回字符串的第一个字符。
const str = "孟加拉国"; const firstCharacter = str.charAt(0); const secondCharacter = str.charAt(1); console.log (firstCharacter) console.log (secondCharacter)
已经12年了,只有一个开发人员提到了regexp,但它是一种更简单的方法:
const str = 'string';
str.match(/\w/); // >> s
它将返回给定字符串中的第一个字符类单词。
如果charAt()有父道具,则不工作 前女友parent.child.chartAt (0) 使用parent.child。片(0,1)