如何获得字符串的第一个字符?

我有一个字符串,我需要获取它的第一个字符。

var x = 'somestring';
alert(x[0]); //in ie7 returns undefined

如何修复我的代码?

猿路易2020/03/12 11:27:00

Try this as well:

x.substr(0, 1);
小小JinJin蛋蛋2020/03/12 11:27:00

x.substring(0,1)

Details

substring(start, end) extracts the characters from a string, between the 2 indices "start" and "end", not including "end" itself.

Special notes

  • If "start" is greater than "end", this method will swap the two arguments, meaning str.substring(1, 4) == str.substring(4, 1).
  • If either "start" or "end" is less than 0, it is treated as if it were 0.
GOMandy2020/03/12 11:27:00
var str="stack overflow";

firstChar  = str.charAt(0);

secondChar = str.charAt(1);

Tested in IE6+, FF, Chrome, safari.

老丝Stafan2020/03/12 11:27:00

Looks like I am late to the party, but try the below solution which I personally found the best solution:

var x = "testing sub string"
alert(x[0]);
alert(x[1]);

Output should show alert with below values: "t" "e"

2020/03/12 11:27:00

您可以使用任何这些。

所有这些之间都没有什么区别,因此在条件语句中使用它时要小心。

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


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
猴子Davaid2020/03/12 11:27:00

You can even use slice to cut-off all other characters:

x.slice(0, 1);
路易Green2020/03/12 11:27:00

所有方法的例子

首先string.charAt(index)

返回索引处的caract index

var str = "Stack overflow";

console.log(str.charAt(0));

第二string.substring(start,length);

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

在这里,您只想要第一个caract,所以:start = 0length = 1

var str = "Stack overflow";

console.log(str.substring(0,1));

替代方案string[index]

字符串是caract的数组。这样您就可以像阵列的第一个单元格一样获得第一个字符。

index在字符串的索引处返回caract

var str = "Stack overflow";

console.log(str[0]);

仲羽蛋蛋2020/03/12 11:27:00
var x = "somestring"
alert(x.charAt(0));

The charAt() method allows you to specify the position of the character you want.

What you were trying to do is get the character at the position of an array "x", which is not defined as X is not an array.