EN
TypeScript - get first 3 characters of string
0 points
In this short article, we would like to show you how to get the first 3 characters of a string in TypeScript.
The below example shows the use of substring()
method which returns the part of a string between the 0
and 3
indexes.
Runnable example:
xxxxxxxxxx
1
const text: string = '12345';
2
const substring: string = text.substring(0, 3);
3
4
console.log('text: ' + text); // 12345
5
console.log('substring: ' + substring); // 123
Output:
xxxxxxxxxx
1
text: 12345
2
substring: 123
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:
xxxxxxxxxx
1
// ONLINE-RUNNER:browser;
2
3
// true means string is empty
4
5
console.log(''.substring(0, 3) === ''); // empty
6
console.log('1'.substring(0, 3)); // 1
7
console.log('12'.substring(0, 3)); // 12
8
console.log('123'.substring(0, 3)); // 123
9
console.log('1234'.substring(0, 3)); // 123
10
console.log('12345'.substring(0, 3)); // 123
Output:
xxxxxxxxxx
1
true
2
1
3
12
4
123
5
123
6
123
Note:
Don't usesubstr()
because it's a non-standard method.