Skip to content

Instantly share code, notes, and snippets.

@kfitfk
Created March 22, 2022 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kfitfk/a5ee898fa16ea29725c2b8690cdeae65 to your computer and use it in GitHub Desktop.
Save kfitfk/a5ee898fa16ea29725c2b8690cdeae65 to your computer and use it in GitHub Desktop.
Get nth or last nth index of a pattern from a string
function nthIndex(str, pat, n){
let i= -1;
while (n-- && i++ < str.length) {
i = str.indexOf(pat, i);
if (i < 0) break;
}
return i;
}
function lastNthIndex(str, pat, n) {
let i = str.length;
while (n-- && i-- > -1) {
i = str.lastIndexOf(pat, i);
if (i < 0) break;
}
return i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment