Created
March 22, 2022 02:19
-
-
Save kfitfk/a5ee898fa16ea29725c2b8690cdeae65 to your computer and use it in GitHub Desktop.
Get nth or last nth index of a pattern from a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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