Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 436
Ageis Avatar asked May 22 '12 21:05

Ageis


People also ask

How do you find all the indexes of a character in a string?

Using indexOf() and lastIndexOf() method The String class provides an indexOf() method that returns the index of the first appearance of a character in a string. To get the indices of all occurrences of a character in a String, you can repeatedly call the indexOf() method within a loop.

How do you find the index of a specific character?

To get the index of a character in a string, you use the indexOf() method, passing it the specific character as a parameter. This method returns the index of the first occurrence of the character or -1 if the character is not found.

How do you find all the index of a character in a string in Python?

We can use the finditer() function inside the re module of Python for our specific problem. The finditer() function takes the pattern and the string as input parameters. It reads the string from left to right and returns all the indexes where the pattern occurs.


2 Answers

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

like image 132
vcsjones Avatar answered Oct 22 '22 08:10

vcsjones


Using the native String.prototype.indexOf method to most efficiently find each offset.

function locations(substring,string){   var a=[],i=-1;   while((i=string.indexOf(substring,i+1)) >= 0) a.push(i);   return a; }  console.log(locations("s","scissors")); //-> [0, 3, 4, 7] 

This is a micro-optimization, however. For a simple and terse loop that will be fast enough:

// Produces the indices in reverse order; throw on a .reverse() if you want for (var a=[],i=str.length;i--;) if (str[i]=="s") a.push(i);     

In fact, a native loop is faster on chrome that using indexOf!

Graph of performance results from the link

like image 29
Phrogz Avatar answered Oct 22 '22 07:10

Phrogz