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);
}

UPDATE

I failed to spot in the original question that the search string needs to be a variable. I've written another version to deal with this case that uses indexOf, so you're back to where you started. As pointed out by Wrikken in the comments, to do this for the general case with regular expressions you would need to escape special regex characters, at which point I think the regex solution becomes more of a headache than it's worth.

function getIndicesOf(searchStr, str, caseSensitive) {
    var searchStrLen = searchStr.length;
    if (searchStrLen == 0) {
        return [];
    }
    var startIndex = 0, index, indices = [];
    if (!caseSensitive) {
        str = str.toLowerCase();
        searchStr = searchStr.toLowerCase();
    }
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        indices.push(index);
        startIndex = index + searchStrLen;
    }
    return indices;
}

var indices = getIndicesOf("le", "I learned to play the Ukulele in Lebanon.");

document.getElementById("output").innerHTML = indices + "";
<div id="output"></div>
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Answer from Tim Down on Stack Overflow
🌐
CodeSignal
codesignal.com › learn › courses › practicing-string-operations-and-type-conversions-in-javascript › lessons › finding-all-substring-occurrences-in-strings-with-javascript
Finding All Substring Occurrences in Strings with JavaScript
To pair original strings with their substrings, we use a simple for loop. In our case, both lists share the same length, so we can use their indices to pair them correctly. To find the first occurrence of each substring in the corresponding original string, we utilize the indexOf method:
Top answer
1 of 16
211
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);
}

UPDATE

I failed to spot in the original question that the search string needs to be a variable. I've written another version to deal with this case that uses indexOf, so you're back to where you started. As pointed out by Wrikken in the comments, to do this for the general case with regular expressions you would need to escape special regex characters, at which point I think the regex solution becomes more of a headache than it's worth.

function getIndicesOf(searchStr, str, caseSensitive) {
    var searchStrLen = searchStr.length;
    if (searchStrLen == 0) {
        return [];
    }
    var startIndex = 0, index, indices = [];
    if (!caseSensitive) {
        str = str.toLowerCase();
        searchStr = searchStr.toLowerCase();
    }
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        indices.push(index);
        startIndex = index + searchStrLen;
    }
    return indices;
}

var indices = getIndicesOf("le", "I learned to play the Ukulele in Lebanon.");

document.getElementById("output").innerHTML = indices + "";
<div id="output"></div>
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 16
68

One liner using String.prototype.matchAll (ES2020):

[...sourceStr.matchAll(new RegExp(searchStr, 'gi'))].map(a => a.index)

Using your values:

const sourceStr = 'I learned to play the Ukulele in Lebanon.';
const searchStr = 'le';
const indexes = [...sourceStr.matchAll(new RegExp(searchStr, 'gi'))].map(a => a.index);
console.log(indexes); // [2, 25, 27, 33]

If you're worried about doing a spread and a map() in one line, I ran it with a for...of loop for a million iterations (using your strings). The one liner averages 1420ms while the for...of averages 1150ms on my machine. That's not an insignificant difference, but the one liner will work fine if you're only doing a handful of matches.

See matchAll on caniuse

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › matchAll
String.prototype.matchAll() - JavaScript - MDN Web Docs
July 10, 2025 - const regexp = /foo[a-z]*/g; const str = "table football, foosball"; const matches = str.matchAll(regexp); for (const match of matches) { console.log( `Found ${match[0]} start=${match.index} end=${ match.index + match[0].length }.`, ); } // Found football start=6 end=14.
🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › String › matchAll
JavaScript String matchAll() - Match All Occurrences | Vultr Docs
November 14, 2024 - Start with a basic string that includes multiple instances of a simple pattern. Define a regular expression to search for the pattern. Use matchAll() to retrieve all matches and convert the iterator to an array for easier manipulation.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-count-string-occurrence-in-string-using-javascript
JavaScript - How To Count String Occurrence in String? - GeeksforGeeks
July 11, 2025 - You can manually iterate through the string to count occurrences by checking for the substring at each position. ... const s1 = "hello world, hello JavaScript!"; const s2 = "hello"; let count = 0; let pos = 0; while ((pos = s1.indexOf(s2, pos)) ...
🌐
YouTube
youtube.com › watch
JavaScript Problem: Finding All Occurrences of a Character in a String - YouTube
In today's tutorial we are going to deal with a JavaScript problem that has to do with analyzing a string. We will create a function that will accept a strin...
Published   March 17, 2021
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › string › all indexes of substring
Find all indexes of a substring in a JavaScript string - 30 seconds of code
March 10, 2024 - In order to find all indexes of a substring, I find it useful to create a generator function. This provides a little more flexibility and might be more efficient in some cases. As mentioned already, String.prototype.indexOf() only returns the first occurrence of a substring, but it can be passed a second argument, fromIndex, which specifies the index at which to start the search.
Find elsewhere
🌐
CodingTechRoom
codingtechroom.com › question › -indexof-find-all-occurrences-string
How to Use indexOf to Find All Occurrences of a Word in a String - CodingTechRoom
function findAllOccurrences(str, word) { let indices = [], startIndex = 0; while (startIndex < str.length) { const index = str.indexOf(word, startIndex); if (index === -1) break; // No more occurrences indices.push(index); // Store the found index startIndex = index + word.length; // Update ...
🌐
W3docs
w3docs.com › javascript
How to Count String Occurrence in String
One of the solution can be provided by the match() function, which is used to generate all the occurrences of a string in an array. By counting the array size that returns the number of times the substring present in a string.
🌐
TutorialsPoint
tutorialspoint.com › find-all-occurrences-of-a-word-in-array-in-javascript
Find all occurrences of a word in array in JavaScript
We are required to write a JavaScript function that takes in an array of literals as the first argument and a string as the second argument. Our function should return the count of the number of times that string (provided by second argument) appears anywhere in the array. ... const arr = ["word", "a word", "another word"]; const query = "word"; const findAll = (arr, query) => { let count = 0; count = arr.filter(el => { return el.indexOf(query) != -1; }).length; return count; }; console.log(findAll(arr, query));
🌐
GitHub
gist.github.com › 1754313
Find all the occurrences of every string in a JS file. · GitHub
July 16, 2017 - Find all the occurrences of every string in a JS file. - analyze.js
🌐
Stack Abuse
stackabuse.com › javascript-how-to-count-the-number-of-substring-occurrences-in-a-string
JavaScript: How to Count the Number of Substring Occurrences in a String
April 7, 2023 - But in this article, we'll use it to count the number of occurrences of a substring in a string. If you want to get to know more about regular expressions in JavaScript, you should read our comprehensive guide - "Guide to Regular Expressions and Matching Strings in JavaScript". First of all, we need to define a regular expression that will match the substring we are looking for. Assuming we want to find the number of occurrences of the string "orange" in a larger string, our regular expression will look as follows:
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-count-string-occurrence-in-string-using-javascript
JavaScript – How To Count String Occurrence in String? | GeeksforGeeks
November 27, 2024 - Here are the various methods to count string occurrence in a string using JavaScript. The match() method is a simple and effective way to count occurrences using a regular expression. It returns an array of all matches, and the length of the ...
🌐
W3Resource
w3resource.com › javascript-exercises › javascript-string-exercise-18.php
JavaScript validation with regular expression: Count the occurrence of a substring in a string - w3resource
July 17, 2025 - If 'sub_str' is an empty string or undefined, the function returns the length of 'main_str' plus 1. It escapes special characters in 'sub_str' using a regular expression. It counts the occurrences of 'sub_str' in 'main_str' using a global case-insensitive regular expression match and returns the count.
🌐
Programiz
programiz.com › javascript › examples › check-occurrence-string
JavaScript Program to Check the Number of Occurrences of a Character in the String
In the above example, a regular expression (regex) is used to find the occurrence of a string. const re = new RegExp(letter, 'g'); creates a regular expression. The match() method returns an array containing all the matches.
🌐
CodingNomads
codingnomads.com › match-string-javascript
JavaScript String Matching
This flag tells the regular expression to match all occurrences of the pattern in the string. Without this flag, the regular expression will only match the first occurrence of the pattern. The way you turn a primitive JavaScript string into a regular expression is by wrapping it in forward ...