How to get the text after a specific word with JavaScript?

Sometimes, we want to get the text after a specific word with JavaScript.

In this article, we’ll look at how to get the text after a specific word with JavaScript.

How to get the text after a specific word with JavaScript?

To get the text after a specific word with JavaScript, we can use some string methods.

For instance, we write:

const x = 'foobarbaz'
const y = 'bar'
const z = x.slice(x.indexOf(y) + y.length);
console.log(z)

to get the part of x after 'bar'.

To do this, we call x.slice with the index of the first character of y, which we get from indexOf.

We didn’t pass in a second argument to slice, so the end index is the end of the string.

Then we add y.length to it to get the last index of 'bar' in x.

Therefore, z is 'baz'.

Conclusion

To get the text after a specific word with JavaScript, we can use some string methods.