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