我有一个字符串,我需要得到它的第一个字符。
Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined
如何修复我的代码?
我有一个字符串,我需要得到它的第一个字符。
Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined
如何修复我的代码?
当前回答
你可以使用以下任何一种:
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
其他回答
你可以用任何一个。
所有这些都有一点不同 所以在条件语句中使用时要小心。
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
你甚至可以使用切片切断所有其他字符:
x.slice(0, 1);
由于每个字符串都是一个数组,可能最简洁的解决方案是使用新的展开操作符:
const x = 'somestring'
const [head, ...tail] = x
console.log(head) // 's'
额外的好处是你现在可以访问整个字符串,但第一个字符使用join(")在尾部:
console.log(tail.join('')) // 'omestring'
Const x = 'some string'; console.log (x。substring (0,1));
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。