javascriptregexmatchstring-matching

Return positions of a regex match() in Javascript?


Is there a way to retrieve the (starting) character positions inside a string of the results of a regex match() in Javascript?


Solution

  • Here's what I came up with:

    // Finds starting and ending positions of quoted text
    // in double or single quotes with escape char support like \" \'
    var str = "this is a \"quoted\" string as you can 'read'";
    
    var patt = /'((?:\\.|[^'])*)'|"((?:\\.|[^"])*)"/igm;
    
    while (match = patt.exec(str)) {
      console.log(match.index + ' ' + patt.lastIndex);
    }