Skip to content
Advertisement

Finding all indexes of a specified character within a string

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

Advertisement

Answer

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.

enter image description here

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement