我有一个字符串,我需要得到它的第一个字符。
Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined
如何修复我的代码?
我有一个字符串,我需要得到它的第一个字符。
Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined
如何修复我的代码?
当前回答
在JavaScript中,你可以这样做:
Const x = 'some string'; console.log (x。substring (0,1));
其他回答
你甚至可以使用切片切断所有其他字符:
x.slice(0, 1);
看起来我迟到了,但试试下面的解决方案,我个人认为最好的解决方案:
var x = "testing sub string"
alert(x[0]);
alert(x[1]);
输出应该显示警报与以下值: “t” “e”
已经12年了,只有一个开发人员提到了regexp,但它是一种更简单的方法:
const str = 'string';
str.match(/\w/); // >> s
它将返回给定字符串中的第一个字符类单词。
你可以使用以下任何一种:
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
已经10年了,还没有人提到RegExp。
var x = 'somestring'; console.log(x.match(/./)[0]);