返回 Javascript 中正则表达式 match() 的位置?

2022-08-30 01:10:12

有没有办法在Javascript中检索正则表达式match()结果字符串中的(起始)字符位置?


答案 1

exec 返回一个具有属性的对象:index

var match = /bar/.exec("foobar");
if (match) {
    console.log("match found at " + match.index);
}

对于多场比赛:

var re = /bar/g,
    str = "foobarfoobar";
while ((match = re.exec(str)) != null) {
    console.log("match found at " + match.index);
}

答案 2

以下是我想出的:

// 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);
}