How to get first character of string?
charAt
can give wrong results for Unicode. Use Array.from
:
Array.from('some string')[0];
In JavaScript you can do this:
const x = 'some string';
console.log(x.substring(0, 1));
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
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