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
Last updated: Mar 1, 2024 Reading timeยท4 min ยท Use the String.indexOf() method to get the index of a character in a string
Discussions

javascript - Find the indexs of all occerences a character in a string - Stack Overflow
How to find all occurrences of a character in a string. For example string is: "Hello world" and user want to now the indexes of string where 'L' is present. Which is in example 2,3 and 9. How to f... More on stackoverflow.com
๐ŸŒ stackoverflow.com
javascript - Get characters index in string - Stack Overflow
I want to achieve something like this: if array [ "a", "b", "c"] includes any of the characters of const word = "abracadabra" give me that character and its 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
๐ŸŒ
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
const str = "ใƒปWelcome to ใƒปStackOverFlow ใƒปBest Regards"; let bullet_ndx = []; let index = 0; while((index = str.indexOf("ใƒป", index))>=0) bullet_ndx.push(index++); console.log(bullet_ndx);
๐ŸŒ
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.
๐ŸŒ
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 provides several built-in String methods that make this task simple and efficient. This guide will teach you how to use indexOf() to find the first occurrence, lastIndexOf() to find the last occurrence, and a simple loop to find all occurrences of a character in a string.
๐ŸŒ
FindCodeExample
findcodeexample.com โ€บ tutorial โ€บ finding-all-indexes-of-a-specified-character-within-a-string
Finding all indexes of a specified character within a string - Javascript
September 6, 2022 - The charAt () method returns a character at a specified index. During each iteration, if the character at that index matches the required character to match, then the count variable is increased by 1. Example 2: Check occurrence of a character using a Regex ...
Find elsewhere
๐ŸŒ
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 - 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
๐ŸŒ
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
๐ŸŒ
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
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript"> window.onload=function(){/* w w w .jav a 2 s .co m*/ var str = "abcdab"; var re = /a/g; var matches; var indexes = []; while (matches = re.exec(str)) { indexes.push(matches.index); }
๐ŸŒ
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.
๐ŸŒ
BigBinary Academy
courses.bigbinaryacademy.com โ€บ learn-javascript โ€บ string-methods โ€บ finding-index-of-character-in-string
Finding Index of Character in String - Learn JavaScript | BigBinary Academy
There are a couple of ways in which we can find if a string contains another string or **substring**. The `indexOf()` method helps us locate a substring inside a string. The method accepts two arguments - **substring** and **fromIndex**. The default value of **fromIndex** is `0`. Let's take ...
๐ŸŒ
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
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.
๐ŸŒ
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 two lists of strings, both of identical lengths โ€” the first containing the "original" strings and the second containing the substrings. 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 0.
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