3

I just wish to find the start and end positions of the substrings I am searching for. Any Ideas as to how this can be done?

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
user918671
  • 39
  • 1
  • 2
  • What have you tried? Where did it fail? What mark-up or JavaScript are you using? – David Thomas Aug 29 '11 at 22:54
  • 1
    Questions that don't show that the OP put any effort really make me sad. – Ruan Mendes Aug 29 '11 at 23:08
  • I agree Juan, and it seems all too common with userNNNNNN accounts in particular. – Stephen P Aug 30 '11 at 00:10
  • 1
    @JuanMendes We shouldn't criticize people for asking useful questions like this one: the answer wasn't obvious to me either, so I'm grateful that this question was posted. – Anderson Green Sep 19 '13 at 03:54
  • @AndersonGreen Like it or not, a question without effort is a poor one. If you do that at work, you won't get anywhere. Asking to show what you tried is constructive citicism. I don't think anyone was rude. Asking questions without showing enough effort is impolite if you ask me. – Ruan Mendes Sep 19 '13 at 06:42
  • Possible duplicate of [Return positions of a regex match() in Javascript?](http://stackoverflow.com/questions/2295657/return-positions-of-a-regex-match-in-javascript) – Ruslan López Jun 24 '16 at 17:09

2 Answers2

8

Here's a jsfiddle that shows how it's done...

https://jsfiddle.net/cz8vqgba/

var regex = /text/g;
var text = 'this is some text and then there is some more text';
var match;
while(match = regex.exec(text)){
    console.log('start index= ' +(regex.lastIndex - match[0].length));   
    console.log('end index= ' + (regex.lastIndex-1));
}

This will get you the start and end index of all matches in the string...

Gras Double
  • 15,901
  • 8
  • 56
  • 54
gislikonrad
  • 3,401
  • 2
  • 22
  • 24
7

no need at all to traverse the haystack two times (which would likely be less efficient)

you can do either:

"foobarfoobar".match(/bar/);

or:

/bar/.exec("foobarfoobar");

both return this object :

{
    0: 'bar'
    index: 3
    input: 'foobarfoobar'
}

so if you want start and end positions, you just have to do something like:

var needle = /bar/;
var haystack = 'foobarfoobar';

var result = needle.exec(haystack);
var start = result.index;
var end = start + result[0].length - 1;

Note this simple example gives you only the first match; if you expect several matches, things get a little bit more complicated.

Also, I answered for regex as it is in the title of the question, but if all you need is string match you can do nearly the same with indexOf().

Gras Double
  • 15,901
  • 8
  • 56
  • 54