Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the nth occurrence in a string?

Tags:

javascript

I would like to get the starting position of the 2nd occurrence of ABC with something like this:

var string = "XYZ 123 ABC 456 ABC 789 ABC";
getPosition(string, 'ABC', 2) // --> 16

How would you do it?

like image 674
Adam Halasz Avatar asked Oct 07 '22 21:10

Adam Halasz


People also ask

How do you find the nth occurrence of a character in a string?

1) Select Lookup from the drop-down list of Formula Type section; 2) Choose Find where the character appear Nth in a string in Choose a formula section; 3) Select the cell which contains the string you use, then type the specified character and nth occurrence in to the textboxes in the Arguments input section.

How do you find the nth occurrence of a character in a string in python?

You can find the nth occurrence of a substring in a string by splitting at the substring with max n+1 splits. If the resulting list has a size greater than n+1, it means that the substring occurs more than n times.


1 Answers

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

function getPosition(string, subString, index) {
  return string.split(subString, index).join(subString).length;
}

console.log(
  getPosition(string, 'ABC', 2) // --> 16
)
like image 200
Denys Séguret Avatar answered Oct 12 '22 19:10

Denys Séguret