Sometimes, we want to get a substring that comes after a separator with JavaScript.
In this article, we’ll look at how to get a substring that comes after a separator with JavaScript.
Get a Substring that Comes After a Separator with JavaScript
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' .
Conclusion
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.