To find the kth index of a substring in a string in JavaScript, you can use a combination of the indexOf() and slice() methods.
Here's an example function that takes a string str, a substring substr, and a positive integer k, and returns the index of the k-th occurrence of substr in str. If there are fewer than k occurrences of substr, the function returns -1.
index.tsx185 chars11 linesHere's an example usage:
index.tsx146 chars6 lines
In this example, the string str contains six occurrences of the substring ".". The kthIndex() function returns the index of the third occurrence (i.e., k=3) of ".", which is 16.
Note that this function assumes that k is a positive integer. If k is negative or zero, the function returns -1.
gistlibby LogSnag