EN
JavaScript - get first character of string
0 points
In this short article, we would like to show you how to get the first character of a string in JavaScript.
Below example shows the use of .substring()
method which returns the part of a string between the 0
and 1
indexes.
Runnable example:
xxxxxxxxxx
1
var text = '123';
2
var substring = text.substring(0,1);
3
4
console.log("text: " + text); // 123
5
console.log("substring: " + substring); // 1
In the second example, we can see the result when we want to get a substring from a string in various cases (like string shorter than the number of characters we want to get or an empty string).
Runnable example:
xxxxxxxxxx
1
// true means string is empty
2
3
console.log( "".substring(0, 1) === "" ); // empty
4
console.log( "1".substring(0, 1) ); // 1
5
console.log( "12".substring(0, 1) ); // 1
6
console.log( "123".substring(0, 1) ); // 1
Note:
Don't usesubstr()
because it's a non-standard method.