Languages
[Edit]
EN

JavaScript - get substring before word

0 points
Created by:
Olivier-Myers
364

In this article, we would like to show you how to get substring before a word in JavaScript​​​​​​.

Quick solution:

// ONLINE-RUNNER:browser;

const text = 'This is example text...';
const word = 'example';

const index = text.indexOf(word);   // 8
const result = 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. 

// ONLINE-RUNNER:browser;

const text = 'This is example text...';
const word = 'example';

const textArray = text.split(word);     // ['This is ', ' text...']
const result = textArray.shift();       // 'This is '

console.log(result);  // 'This is '

References

  1. String.prototype.split() - JavaScript | MDN
  2. Array.prototype.shift() - JavaScript | MDN
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join