我有一个字符串,我需要得到它的第一个字符。

Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined

如何修复我的代码?


当前回答

在Nodejs中你可以使用Buffer:

let str = "hello world"
let buffer = Buffer.alloc(2, str) // replace 2 by 1 for the first char
console.log(buffer.toString('utf-8')) // display he
console.log(buffer.toString('utf-8').length) // display 2

其他回答

你甚至可以使用切片切断所有其他字符:

x.slice(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

如果charAt()有父道具,则不工作 前女友parent.child.chartAt (0) 使用parent.child。片(0,1)

所有方法示例

第一个:string.charAt(index)

返回索引index处的caract

var str = “堆栈溢出”; console.log(str.charAt(0));

第二个:string.substring(start,length);

返回字符串中从索引start开始并在长度length之后停止的子字符串

这里你只需要第一个caract: start = 0 and length = 1

var str = “堆栈溢出”; console.log(str.substring(0,1));

string[index]

字符串是一个caract数组。所以你可以得到第一个caract就像数组的第一个单元格。

返回字符串的下标处的caract

var str = “堆栈溢出”; console.log(str[0]);

由于每个字符串都是一个数组,可能最简洁的解决方案是使用新的展开操作符:

const x = 'somestring'
const [head, ...tail] = x
console.log(head) // 's'

额外的好处是你现在可以访问整个字符串,但第一个字符使用join(")在尾部:

console.log(tail.join('')) // 'omestring'