How to get the nth occurrence in a string?

I would like to get the starting position for the appearance of 2nd ABC . Something like that:

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

How do you do this?

+56
javascript
Jan 23 '13 at 13:00
source share
8 answers
 function getPosition(string, subString, index) { return string.split(subString, index).join(subString).length; } 
+98
Jan 23 '13 at 13:01
source share

You can also use the indexOf string without creating any arrays.

The second parameter is the index that starts looking for the next match.

 function nthIndex(str, pat, n){ var L= str.length, i= -1; while(n-- && i++<L){ i= str.indexOf(pat, i); if (i < 0) break; } return i; } var s= "XYZ 123 ABC 456 ABC 789 ABC"; nthIndex(s,'ABC',3) 

/ * return value: (Number) 24 * /

+26
Jan 23 '13 at 14:31
source share

Turning off kennebec's answer, I created a prototype function that will return -1 if the n-th place is not found, and not 0.

 String.prototype.nthIndexOf = function(pattern, n) { var i = -1; while (n-- && i++ < this.length) { i = this.indexOf(pattern, i); if (i < 0) break; } return i; } 
+14
Dec 15 '13 at 19:42
source share

Because recursion is always the answer.

 function getPosition(input, search, nth, curr, cnt) { curr = curr || 0; cnt = cnt || 0; var index = input.indexOf(search); if (curr === nth) { if (~index) { return cnt; } else { return -1; } } else { if (~index) { return getPosition(input.slice(index + search.length), search, nth, ++curr, cnt + index + search.length); } else { return -1; } } } 
+2
Jan 23 '13 at 13:15
source share

Here's my solution, which simply iterates through the string until n matches are found:

 String.prototype.nthIndexOf = function(searchElement, n, fromElement) { n = n || 0; fromElement = fromElement || 0; while (n > 0) { fromElement = this.indexOf(searchElement, fromElement); if (fromElement < 0) { return -1; } --n; ++fromElement; } return fromElement - 1; }; var string = "XYZ 123 ABC 456 ABC 789 ABC"; console.log(string.nthIndexOf('ABC', 2)); >> 16 
+2
Jan 23 '13 at 14:00
source share

This method creates a function that calls the index of the nth occurrence stored in the array

 function nthIndexOf(search, n) { var myArray = []; for(var i = 0; i < myString.length; i++) { //loop thru string to check for occurrences if(myStr.slice(i, i + search.length) === search) { //if match found... myArray.push(i); //store index of each occurrence } } return myArray[n - 1]; //first occurrence stored in index 0 } 
0
May 31 '16 at 15:00
source share

I played with the following code for another question in StackOverflow and thought it might be appropriate here. The printList2 function allows you to use a regular expression and lists all occurrences in order. (printList was an attempt at an earlier solution, but in some cases it failed).

 <html> <head> <title>Checking regex</title> <script> var string1 = "123xxx5yyy1234ABCxxxabc"; var search1 = /\d+/; var search2 = /\d/; var search3 = /abc/; function printList(search) { document.writeln("<p>Searching using regex: " + search + " (printList)</p>"); var list = string1.match(search); if (list == null) { document.writeln("<p>No matches</p>"); return; } // document.writeln("<p>" + list.toString() + "</p>"); // document.writeln("<p>" + typeof(list1) + "</p>"); // document.writeln("<p>" + Array.isArray(list1) + "</p>"); // document.writeln("<p>" + list1 + "</p>"); var count = list.length; document.writeln("<ul>"); for (i = 0; i < count; i++) { document.writeln("<li>" + " " + list[i] + " length=" + list[i].length + " first position=" + string1.indexOf(list[i]) + "</li>"); } document.writeln("</ul>"); } function printList2(search) { document.writeln("<p>Searching using regex: " + search + " (printList2)</p>"); var index = 0; var partial = string1; document.writeln("<ol>"); for (j = 0; j < 100; j++) { var found = partial.match(search); if (found == null) { // document.writeln("<p>not found</p>"); break; } var size = found[0].length; var loc = partial.search(search); var actloc = loc + index; document.writeln("<li>" + found[0] + " length=" + size + " first position=" + actloc); // document.writeln(" " + partial + " " + loc); partial = partial.substring(loc + size); index = index + loc + size; document.writeln("</li>"); } document.writeln("</ol>"); } </script> </head> <body> <p>Original string is <script>document.writeln(string1);</script></p> <script> printList(/\d+/g); printList2(/\d+/); printList(/\d/g); printList2(/\d/); printList(/abc/g); printList2(/abc/); printList(/ABC/gi); printList2(/ABC/i); </script> </body> </html> 
0
Jun 30 '16 at 4:00
source share

Using indexOf and Recursion :

First check if the nth position is exceeded than the total number of occurrences of the substring. If they are passed recursively scan each index until the nth is found.

 var getNthPosition = function(str, sub, n) { if (n > str.split(sub).length - 1) return -1; var recursePosition = function(n) { if (n === 0) return str.indexOf(sub); return str.indexOf(sub, recursePosition(n - 1) + 1); }; return recursePosition(n); }; 
0
Aug 30 '17 at 2:05 on
source share



All Articles