Categories
JavaScript Answers

How to get the nth occurrence in a string with JavaScript?

Spread the love

Sometimes, we want to get the nth occurrence in a string with JavaScript.

In this article, we’ll look at how to get the nth occurrence in a string with JavaScript.

How to get the nth occurrence in a string with JavaScript?

To get the nth occurrence in a string with JavaScript, we can use the split and join methods.

For instance, we write

const string = "XYZ 123 ABC 456 ABC 789 ABC";

const getPosition = (string, subString, index) => {
  return string.split(subString, index).join(subString).length;
};

console.log(
  getPosition(string, "ABC", 2)
);

to define the getPosition function.

In it, we call string.split with subString and index to split the string starting at index with subString as the separator.

Then we call join with subString to join the returned string array back into a string and get its length.

Then we get the start index of the 2nd 'ABC' with getPosition(string, "ABC", 2).

Conclusion

To get the nth occurrence in a string with JavaScript, we can use the split and join methods.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *