我有一个字符串,我需要得到它的第一个字符。
Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined
如何修复我的代码?
我有一个字符串,我需要得到它的第一个字符。
Var x = 'somestring'; 警报(x [0]);//在ie7中返回undefined
如何修复我的代码?
当前回答
所有方法示例
第一个: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]);
其他回答
已经12年了,只有一个开发人员提到了regexp,但它是一种更简单的方法:
const str = 'string';
str.match(/\w/); // >> s
它将返回给定字符串中的第一个字符类单词。
你也可以试试这个:
x.substr(0, 1);
如果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
你甚至可以使用切片切断所有其他字符:
x.slice(0, 1);