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
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.
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.
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.
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.
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
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With