find the kth index of a substring in a string in javascript

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.tsx
function kthIndex(str, substr, k) {
  var idx = -1;
  for (var i = 0; i < k; i++) {
    idx = str.indexOf(substr, idx + 1);
    if (idx === -1) {
      break;
    }
  }
  return idx;
}
185 chars
11 lines

Here's an example usage:

index.tsx
var str = "one.two.three.four.five.six.seven";
var substr = ".";
var k = 3;
var idx = kthIndex(str, substr, k);
console.log(idx);  // outputs: 16
146 chars
6 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