EN
TypeScript - get substring before word
0
points
In this article, we would like to show you how to get substring before a word in TypeScript.
Quick solution:
const text: string = 'This is example text...';
const word: string = 'example';
const index: number = text.indexOf(word); // 8
const result: string = text.slice(0, index);
console.log(result); // 'This is '
Practical example
In this example, we use split() method to split the text string into array by the specified word. Then we use shift() method to get the first element (index 0) from the textArray array.
const text: string = 'This is example text...';
const word: string = 'example';
const textArray: string[] = text.split(word); // ['This is ', ' text...']
const result: string = textArray.shift(); // 'This is '
console.log(result); // 'This is '