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:
xxxxxxxxxx
1
const text: string = 'This is example text...';
2
const word: string = 'example';
3
4
const index: number = text.indexOf(word); // 8
5
const result: string = text.slice(0, index);
6
7
console.log(result); // 'This is '
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.
xxxxxxxxxx
1
const text: string = 'This is example text...';
2
const word: string = 'example';
3
4
const textArray: string[] = text.split(word); // ['This is ', ' text...']
5
const result: string = textArray.shift(); // 'This is '
6
7
console.log(result); // 'This is '