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

To find the kth index of a substring in a string in TypeScript, you can use the indexOf function in a loop until the kth occurrence is found. The indexOf function returns the first occurrence of the specified substring or character in a string. Here's an example implementation:

index.ts
function findKthIndex(str: string, substr: string, k: number): number {
  let index = -1;
  for (let i = 0; i < k; i++) { // loop 'k' times to find the kth occurrence
    index = str.indexOf(substr, index + 1); // search for substring starting from (index + 1) position
    if (index === -1) { // if substring not found, return -1
      break;
    }
  }
  return index;
}
372 chars
11 lines

In this implementation:

  • str is the input string
  • substr is the substring to search for
  • k is the kth occurrence of the substring to find (1-based indexing)
  • index is the index position of the last-found occurrence of the substring
  • The loop runs k times and searches for the substring using indexOf function, starting from the (last-found index position + 1).
  • If the substring is not found at any step, the function returns -1

You can call the findKthIndex function like this:

index.ts
const str = "hello world, here's a substring";
const substr = "o";
const k = 3;
const index = findKthIndex(str, substr, k); // returns 12
138 chars
5 lines

In this example, the function returns 12 because the third occurrence of substring 'o' is at position 12 in the input string.

gistlibby LogSnag