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 * /
kennebec Jan 23 '13 at 14:31 2013-01-23 14:31
source share