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.ts372 chars11 lines
In this implementation:
str
is the input stringsubstr
is the substring to search fork
is the kth occurrence of the substring to find (1-based indexing)index
is the index position of the last-found occurrence of the substringk
times and searches for the substring using indexOf
function, starting from the (last-found index position + 1).-1
You can call the findKthIndex
function like this:
index.ts138 chars5 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