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 string le
, I want to obtain the array:
[2, 25, 27, 33]
Both strings will be variables - i.e., I can't hard-code their values.
I figured that this was an easy task for regular expressions, but after struggling for a while to find one that would work, I've had no luck.
I found this example of how to accomplish this using .indexOf()
, but surely there has to be a more concise way to do it?
If you just want to find the position of all matches I'd like to point you to a little hack:
it might not be applikable if you have a RegExp with variable length but for some it might be helpful.
Follow the answer of @jcubic, his solution caused a small confuse for my case
For example
var result = indexes('aaaa', 'aa')
it will return[0, 1, 2]
instead of[0, 2]
So I updated a bit his solution as below to match my case
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.the below code will do the job for you :
You sure can do this!
Edit: learn to spell RegExp
Also, I realized this isn't exactly what you want, as
lastIndex
tells us the end of the needle not the beginning, but it's close - you could pushre.lastIndex-needle.length
into the results array...Edit: adding link
@Tim Down's answer uses the results object from RegExp.exec(), and all my Javascript resources gloss over its use (apart from giving you the matched string). So when he uses
result.index
, that's some sort of unnamed Match Object. In the MDC description of exec, they actually describe this object in decent detail.