var str = "I learned to play the Ukulele in Lebanon."
var regex = /le/gi, result, indices = [];
while ( (result = regex.exec(str)) ) {
indices.push(result.index);
}
console.log(indices) // => [2, 25, 27, 33]
//find all occurence of le and return the return an array of the indeces
function getIndicesOf(searchStr: string, str: string, caseSensitive?: boolean) {
const searchStrLen = searchStr.length
if (searchStrLen === 0) {
return []
}
let startIndex = 0
let index: number
const indices: number[] = []
if (!caseSensitive) {
str = str.toLowerCase()
searchStr = searchStr.toLowerCase()
}
// eslint-disable-next-line no-cond-assign
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index)
startIndex = index + searchStrLen
}
return indices
}