Jump to content

Split a String and then find the indexOf() multiple instances of a string


monkeytooth

Recommended Posts

Lets say I have a string

 

var myString = "I was sitting at the green light thinking about the Green Hornet and thought about the greenish tints he had on the windows";

 

I need to split the string so its broken down by spaces like a CSV but just the space.. Then I need to find every instance of "green" but case sensitive, any ideas? I thought I had an idea but I just ended up doing something entirely wrong... What I need my output to look like is

 

20, 45, 50.. (thats not exact but just for the sake of sample). What i need to know is the indexOf() splitting it into an array is for something else. which the spliting I have an understanding of.. Its the indexOf for multiple instances thats got me confused.

You want to split it by the space first, so that it's an array? I'm a bit confused by your question.

 

With the indexOf() method you can supply a second parameter as a start point, however the issue will come up when indexOf() actually finds nested words. So in your example it would find the "green" at the start of "greenish". The other way you can do it is by using regexp in JS, with match(). Of course match will only find the occurring strings and not actually return the location of them.

 

What exactly do you need this for, might be easier to provide a better and more suited solution. :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.