0

Was trying to refer to this (Return positions of a regex match() in Javascript?) to extract beginning and ending position of matches in a particular string but somehow it only returns 1 match. Not sure what I'm doing wrong.

var str = "abc <span djsodjs> ajsodjoasd <spandskds>";

var patt = /.*(<span.*>).*/igm;

while (match = patt.exec(str)) {
    console.log(match.index + ' ' + patt.lastIndex);
}

returns 0 41

expected:

0  41
4  17
30 40
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
Stanley
  • 2,518
  • 4
  • 19
  • 41

1 Answers1

0

if you want index for tag only then you should match only that tag in regex, so you will find the particular that tags values.

Try below code:

var str = "abc <span djsodjs> ajsodjoasd <spandskds>";

var patt = /(\<span)([^\<]*)(\>)/igm;

while (match = patt.exec(str)) {
    console.log(match.index + ' ' + patt.lastIndex);
}

This regex will return two values

/(\<span)([^\<]*)(\>)/igm
Arif Rathod
  • 528
  • 2
  • 13