I have a string, and I need to get its first character.
var x = 'somestring';
alert(x[0]); //in ie7 returns undefined
How can I fix my code?
You can use any of these.
There is a little difference between all of these So be careful while using it in conditional statement.
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
Example of all method
First : string.charAt(index)
Return the caract at the index
index
var str = "Stack overflow";
console.log(str.charAt(0));
Second : string.substring(start,length);
Return the substring in the string who start at the index
start
and stop after the lengthlength
Here you only want the first caract so : start = 0
and length = 1
var str = "Stack overflow";
console.log(str.substring(0,1));
Alternative : string[index]
A string is an array of caract. So you can get the first caract like the first cell of an array.
Return the caract at the index
index
of the string
var str = "Stack overflow";
console.log(str[0]);
x.substring(0,1)
substring(start, end)
extracts the characters from a string, between the 2 indices "start" and "end", not including "end" itself.