Languages
[Edit]
EN

JavaScript - get substring after word

0 points
Created by:
Gaia-Kirby
270

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

1. Using slice() method

In this example, we use indexOf() method to get the index of a word substring. Then we use slice() to get the substring from index + length index to the end of the text string.

// ONLINE-RUNNER:browser;

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

const index = text.indexOf(word);   // 8
const length = word.length;			// 7

const result = text.slice(index + length);

console.log(result);  // ' text...'

2. Using split() with pop() method

In this example, we split the text by the word and get the part after it using pop() method.

// ONLINE-RUNNER:browser;

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

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

console.log(result);  // ' text...'

References

  1. String.prototype.split() - JavaScript | MDN
  2. Array.prototype.slice() - 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