A simple loop works well:

var str = "scissors";
var indices = [];
for(var i=0; i<str.length;i++) {
    if (str[i] === "s") indices.push(i);
}

Now, you indicate that you want 1,4,5,8. This will give you 0, 3, 4, 7 since indexes are zero-based. So you could add one:

if (str[i] === "s") indices.push(i+1);

and now it will give you your expected result.

A fiddle can be see here.

I don't think looping through the whole is terribly efficient

As far as performance goes, I don't think this is something that you need to be gravely worried about until you start hitting problems.

Here is a jsPerf test comparing various answers. In Safari 5.1, the IndexOf performs the best. In Chrome 19, the for loop is the fastest.

Answer from vcsjones on Stack Overflow
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-get-index-of-character-in-string
Get Index of First, Last or All occurrences in String in JS | bobbyhadz
Copied!function findIndexes(string, char) { return string .split('') .map((c, idx) => { if (c === char) { return idx; } return -1; }) .filter(element => element !== -1); } const str = 'hello world'; const indexes = findIndexes(str, 'l'); console.log(indexes); // 👉️ [ 2, 3, 9 ] ... The array contains the all indexes of the character in the string. You can learn more about the related topics by checking out the following tutorials: Get the Index of the Max/Min value in Array in JavaScript
Discussions

find all the indexes of certain character in string javascript - Stack Overflow
i have certain string const str = "・Welcome to ・StackOverFlow ・Best Regards"; i want to get all the indexes of the character "・" unfornately the indexOf only gives the first in... More on stackoverflow.com
🌐 stackoverflow.com
arrays - Finding all indexes of a specified word within a string in javascript - Stack Overflow
How to find all Indexes of as specified word within a lengthy string? let word = 'Testing JavaScript, JavaScript is the Best, JavaScript is Ultimate'; Find the Indexes of word "JavaScript" from the More on stackoverflow.com
🌐 stackoverflow.com
regex - How to find indices of all occurrences of one string in another in JavaScript? - Stack Overflow
I'm trying to find the positions of all occurrences of a string in another string, case-insensitive. For example, given the string: I learned to play the Ukulele in Lebanon. and the search strin... More on stackoverflow.com
🌐 stackoverflow.com
Find all index of occurrences of character in a string
Why would you even need the indexOf method? The naive, straightforward approach is to use .charAt and to loop over the characters in the string using a forloop. (TBH, .indexOf does exactly the same under the hood, just adds a starting index and it stops on the first occurrence). Honestly, the only way to learn proper programming is to stop searching for solutions and to sit down and try to work out your own solutions, because otherwise, you get in over your head, as in your case ending with code that you might have been able to somewhat reproduce, but that you don't understand. Start with pen(cil) and paper and try to figure out how you, the person, would address a problem. Only once you have found a solution start thinking about programming it. And don't memorize. Especially not code. Code adapts to the situation and is only the end product, not the starting point. Edit: Very mature move/s of you blocking people that offer help and advice to you just because you feel personally attacked or disagree with what has been said. More on reddit.com
🌐 r/learnjava
10
3
October 7, 2024
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-find-the-index-of-specific-character-in-a-string-in-javascript
JavaScript - Index of a Character in String - GeeksforGeeks
July 23, 2025 - This function returns the index of the given character in a given string. The indexOf() method is a method to find the index of the first occurrence of a specific string within a string.
🌐
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 - const indexOfSubstrings = function* (str, searchValue) { let i = 0; while (true) { const r = str.indexOf(searchValue, i); if (r !== -1) { yield r; i = r + 1; } else return; } }; [...indexOfSubstrings('tiktok tok tok tik tok tik', 'tik')]; // [0, 15, 23] [...indexOfSubstrings('tutut tut tut', 'tut')]; // [0, 2, 6, 10] [...indexOfSubstrings('hello', 'hi')]; // [] ... JavaScript generator functions are an advanced yet very powerful ES6 feature, which you can start using in your code right now. ... Get all the partial substrings of a string in JavaScript using generator functions.
🌐
Stack Overflow
stackoverflow.com › questions › 68630130 › find-all-the-indexes-of-certain-character-in-string-javascript
find all the indexes of certain character in string javascript - Stack Overflow
@StacksQueue Unfortunately, there is not. There is indexOf and lastIndexOf that gives index of the char starting from forward and backwards respectively. You can write some user defined function though.
🌐
Linux Hint
linuxhint.com › get-the-index-of-a-character-in-a-string-in-javascript
Linux Hint – Linux Hint
November 19, 2022 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
The Web Dev
thewebdev.info › home › how to find all indexes of a specified character within a string with javascript?
How to find all indexes of a specified character within a string with JavaScript? - The Web Dev
June 17, 2022 - Then we call matches.map with a ... all indexes of a specified character within a string with JavaScript, we can use the string matchAll method....
🌐
Tutorial Reference
tutorialreference.com › javascript › examples › faq › javascript-how-to-get-index-of-character-in-string
How to Get the Index of a Character in a String in JavaScript | Tutorial Reference
JavaScript's built-in string methods ... the last occurrence, use string.lastIndexOf(char). To find all occurrences, iterate through the string with a for loop and collect the indexes of all matches....
Find elsewhere
🌐
Java2s
java2s.com › example › javascript › string › get-all-indexes-of-a-pattern-in-a-string.html
Get all indexes of a pattern in a string - Javascript String
Get all indexes of a pattern in ... <body> </body> </html> Previous · Next · Find the first occurrence of the letter "e" in a string: String indexOf() Method ·...
🌐
Quora
quora.com › How-can-I-check-the-index-of-a-space-in-a-given-string-using-Javascript
How to check the index of a space in a given string using Javascript - Quora
To check the index (position) of a space character in a JavaScript string, use these methods depending on whether you need the first occurrence, last occurrence, a specific occurrence, or all occurrences. ... For performance on very large strings, indexOf with a start position is efficient; avoid building arrays unless necessary. ... If you are trying to find ...
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-find-the-index-of-specific-character-in-a-string-in-javascript
JavaScript – Index of a Character in String | GeeksforGeeks
November 17, 2024 - It's determined by rearranging characters to find the smallest cha ... There are several methods to iterate over characters of a string in JavaScript. 1. Using for LoopThe classic for loop is one of the most common ways to iterate over a string. Here, we loop through the string by indexing each character based on the string's length.Syntaxfor (statement 1 ; statement 2
🌐
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
🌐
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
Here is this unit's task: We have ... Our goal is to detect all occurrences of each substring within its corresponding original string and, finally, return a list that contains the starting indices of these occurrences. Remember, the index counting should start from ...
🌐
W3Schools
w3schools.com › jsref › jsref_indexof.asp
JavaScript String indexOf() Method
The indexOf() method returns the position of the first occurrence of a value in a string.
🌐
Sololearn
sololearn.com › en › discuss › 2499878 › how-to-find-all-indices-of-a-certain-character-in-a-list-or-string
How to find all indices of a certain character in a list or string
September 16, 2020 - sl_scroll_/de/Discuss/359554/salam-les-amis-jai-un-probleme-en-javascript-est-ce-que-vous-pouvez-me-donnez-des-sites-ou-des-cours-pour-b1-dcouvrir-ce-languPending
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

🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › String › indexOf
JavaScript String indexOf() - Find Character Position | Vultr Docs
November 13, 2024 - The index 7 is returned and logged to the console because 'w' is the eighth character, and index positions start at 0. Define the string and the substring to locate. Use indexOf() to find the starting index of the substring. ... const phrase ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › indexOf
String.prototype.indexOf() - JavaScript - MDN Web Docs
The indexOf() method of String values searches this string and returns the index of the first occurrence of the specified substring. It takes an optional starting position and returns the first occurrence of the specified substring at an index greater than or equal to the specified number.