EN
JavaScript - get substring before word
0 points
In this article, we would like to show you how to get substring before a word in JavaScript.
Quick solution:
xxxxxxxxxx
1
const text = 'This is example text...';
2
const word = 'example';
3
4
const index = text.indexOf(word); // 8
5
const result = 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 = 'This is example text...';
2
const word = 'example';
3
4
const textArray = text.split(word); // ['This is ', ' text...']
5
const result = textArray.shift(); // 'This is '
6
7
console.log(result); // 'This is '