How can I get a startIndex for each match in my RegExp
Question: I'm struggling a bit with a RegExp result. Basically what I want to have, is a
`startIndex` which gives me the exact position for each match related to the
source string. So instead of an array with strings

    
    
    var regex = /(?:\w*) from "(\w*)"/g
    var result = regex.exec('import foo from "foo"');
    console.log(result.slice(1)) // => ["foo"]
    

I would like to have an object something like this:

    
    
    [{
      value: 'foo',
      startIndex: 17
    }]
    

I don't think this is possible without using a special library, so my question
is:

Do you know any library which returns a more precise match information or any
other solution how I can solve it?

Note this is just an example RegExp. In the real application I will have more
than 10 completely different RegExp. Therefore, a dynamic approach is
preferred.

**Addition**

I need this for the next major version of the [GitHub
Linker](https://github.com/github-linker/chrome-extension). Currently the link
replacement is done with a jquery selector, which isn't that flexible and
sometimes wrong. A RegExp will hopefully decrease the overhead so other
developers can easily extend the [GitHub Linker](https://github.com/github-
linker/chrome-extension) with other languages like Ruby, Python .... Currently
just JavaScript is supported.

That's the reason why I'm looking for a solid and flexible solution.

– Thanks


Answer: The accepted answer [here](http://stackoverflow.com/questions/3410464/how-to-
find-all-occurrences-of-one-string-in-another-in-javascript) seems to be
close. I've adapted it somewhat below, and it appears to get near to what was
required.

    
    
    var str = 'import foo from "foo" import bar from "bar"'
    var regex = /(?:\w*) from "(\w*)"/g;
    var output = [];
    while ((result = regex.exec(str))) {
      var  offset = result[0].lastIndexOf(result[1]);
      output.push('Value: ' + result[1] + ', startIndex: ' + (result.index+offset));
    }
    
    document.getElementById('results').innerHTML = output;
    
    
    <div id="results"></div>

