Categories
JavaScript Answers

How to Get a Substring that Comes After a Separator with JavaScript?

Spread the love

To get a substring that comes after a separator with JavaScript, we can use various string methods.

We can use the JavaScript string’s lastIndexOf method to get the last instance of a separator.

Then we can use the JavaScript string’s substr method to get the substring of a string.

For instance, we can write:

const str = "xxx_456";
const strSub = str.substr(str.lastIndexOf("_") + 1);
console.log(strSub)

We have the str string that uses the _ as a separator.

Then we call str.lastIndexOf with '_' to get the index of the last instance of '_' .

Then we add 1 to it to get the substring after the '_' .

And then we call substr to get the substring from str.lastIndexOf(“_”) + 1 to the end of the string.

Therefore, strSub is '456' .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.