我有一个字符串,我需要得到它的第一个字符。
Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined
如何修复我的代码?
我有一个字符串,我需要得到它的第一个字符。
Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined
如何修复我的代码?
当前回答
你可以用任何一个。
所有这些都有一点不同 所以在条件语句中使用时要小心。
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
其他回答
你可以这样用:
'Hello Mr Been'.split(' ').map( item => item.toUpperCase().substring(0, 1)).join(' ');
如果charAt()有父道具,则不工作 前女友parent.child.chartAt (0) 使用parent.child。片(0,1)
对于任何字符串str = "Hello World"
str.split(' ')。map(item => item. touppercase()。substring(0,1))。加入(' ');
输出:H W
你也可以用as:
var x = "somestring";
console.log(x.split("")[0]); // output "s"
这应该适用于旧的浏览器。
由于每个字符串都是一个数组,可能最简洁的解决方案是使用新的展开操作符:
const x = 'somestring'
const [head, ...tail] = x
console.log(head) // 's'
额外的好处是你现在可以访问整个字符串,但第一个字符使用join(")在尾部:
console.log(tail.join('')) // 'omestring'