EN
TypeScript - get substring before character
0 points
In this article, we would like to show you how to get substring before character using TypeScript.
Quick solution:
xxxxxxxxxx
1
const character: string = ':';
2
const string: string = 'user:password';
3
4
const index: number = string.indexOf(character);
5
const substring: string = string.substring(0, index);
6
7
console.log(substring); // user
In this example, we create a reusable function that helps to get the substring before indicated character.
xxxxxxxxxx
1
const getSubstring = (text: string, character: string): string => {
2
const index = text.indexOf(character);
3
return text.substring(0, index);
4
};
5
6
7
// usage example:
8
9
const text1: string = 'value1: some text...';
10
const text2: string = 'value2: some text...';
11
12
const result1: string = getSubstring(text1, ':'); // value1
13
const result2: string = getSubstring(text2, ':'); // value2
14
15
console.log(result1); // value1
16
console.log(result2); // value2