For example, if I had "scissors" in variable and wanted to know the position of all occurrences of the letter "s", it should print out 1, 4, 5, 8.
How can I do this in JavaScript in most efficient way? I don’t think looping through the whole is terribly efficient
A simple loop works well:
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:
and now it will give you your expected result.
A fiddle can be see here.
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.