我有一个字符串,我需要获取它的第一个字符。
var x = 'somestring';
alert(x[0]); //in ie7 returns undefined
如何修复我的代码?
我有一个字符串,我需要获取它的第一个字符。
var x = 'somestring';
alert(x[0]); //in ie7 returns undefined
如何修复我的代码?
x.substring(0,1)
substring(start, end)
extracts the characters from a string, between the 2 indices "start" and "end", not including "end" itself.
var str="stack overflow";
firstChar = str.charAt(0);
secondChar = str.charAt(1);
Tested in IE6+, FF, Chrome, safari.
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"
您可以使用任何这些。
所有这些之间都没有什么区别,因此在条件语句中使用它时要小心。
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
You can even use slice
to cut-off all other characters:
x.slice(0, 1);
所有方法的例子
首先:string.charAt(index)
返回索引处的caract
index
var str = "Stack overflow";
console.log(str.charAt(0));
第二:string.substring(start,length);
返回字符串中的子字符串,该子字符串从索引处开始,
start
在长度后停止length
在这里,您只想要第一个caract,所以:start = 0
和length = 1
var str = "Stack overflow";
console.log(str.substring(0,1));
替代方案:string[index]
字符串是caract的数组。这样您就可以像阵列的第一个单元格一样获得第一个字符。
index
在字符串的索引处返回caract
var str = "Stack overflow";
console.log(str[0]);
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.
Try this as well: