我有一个字符串,我需要得到它的第一个字符。
Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined
如何修复我的代码?
我有一个字符串,我需要得到它的第一个字符。
Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined
如何修复我的代码?
当前回答
在Javascript中有很多方法可以找到字符串的第一个字符。我认为最简单的方法是string.charAt()方法。此方法以索引号作为参数并返回索引值。如果你没有给出任何参数,默认情况下它会返回字符串的第一个字符。
const str = "孟加拉国"; const firstCharacter = str.charAt(0); const secondCharacter = str.charAt(1); console.log (firstCharacter) console.log (secondCharacter)
其他回答
如果charAt()有父道具,则不工作 前女友parent.child.chartAt (0) 使用parent.child。片(0,1)
你可以用任何一个。
所有这些都有一点不同 所以在条件语句中使用时要小心。
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
已经10年了,还没有人提到RegExp。
var x = 'somestring'; console.log(x.match(/./)[0]);
你可以使用以下任何一种:
let userEmail = "email";
console.log(userEmail[0]); // e
console.log(userEmail.charAt(0)); // e
console.log(userEmail.slice(0, 1)); // e
console.log(userEmail.substring(0, 1)); // e
console.log(userEmail.substr(0, 1)); // e
console.log(userEmail.split("", 1).toString()); // e
console.log(userEmail.match(/./)[0]); // e
你也可以试试这个:
x.substr(0, 1);