How to remove the end of a string starting from a given pattern with JavaScript?

Sometimes, we want to remove the end of a string starting from a given pattern with JavaScript.

In this article, we’ll look at how to remove the end of a string starting from a given pattern with JavaScript.

How to remove the end of a string starting from a given pattern with JavaScript?

To remove the end of a string starting from a given pattern with JavaScript, we can use the string’s substring method.

For instance, we write:

const str = "/abcd/efgh/ijkl/xxx-1/xxx-2";
const s = str.substring(0, str.indexOf("xxx"));
console.log(s)

to call str.string with the start and end indexes of str we want to return.

We have str.indexOf("xxx") to get the index of the first character of the first instance of 'xxx'.

And then we call str.substring with the returned index as the end index.

The character at the end index itself is excluded from the string returned by substring.

Therefore, s is '/abcd/efgh/ijkl/'.

Conclusion

To remove the end of a string starting from a given pattern with JavaScript, we can use the string’s substring method.