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:
const character: string = ':';
const string: string = 'user:password';
const index: number = string.indexOf(character);
const substring: string = string.substring(0, index);
console.log(substring); // user
Practical example
In this example, we create a reusable function that helps to get the substring before indicated character.
const getSubstring = (text: string, character: string): string => {
const index = text.indexOf(character);
return text.substring(0, index);
};
// usage example:
const text1: string = 'value1: some text...';
const text2: string = 'value2: some text...';
const result1: string = getSubstring(text1, ':'); // value1
const result2: string = getSubstring(text2, ':'); // value2
console.log(result1); // value1
console.log(result2); // value2