是否有一种方法来检索(开始)字符的位置在一个正则匹配()在Javascript的结果字符串?


当前回答

我很幸运地使用了这个基于matchAll的单行解决方案(我的用例需要一个字符串位置数组)

let regexp = /bar/g;
let str = 'foobarfoobar';

let matchIndices = Array.from(str.matchAll(regexp)).map(x => x.index);

console.log(matchIndices)

输出:[3,9]

其他回答

这是我最近发现的一个很酷的功能,我在主机上尝试了一下,似乎很管用:

var text = "border-bottom-left-radius";

var newText = text.replace(/-/g,function(match, index){
    return " " + index + " ";
});

返回:"border 6 bottom 13 left 18 radius"

看来这就是你要找的东西。

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

function trimRegex(str, regex){
    return str.substr(str.match(regex).index).split('').reverse().join('').substr(str.match(regex).index).split('').reverse().join('');
}

let test = '||ab||cd||';
trimRegex(test, /[^|]/);
console.log(test); //output: ab||cd

or

function trimChar(str, trim, req){
    let regex = new RegExp('[^'+trim+']');
    return str.substr(str.match(regex).index).split('').reverse().join('').substr(str.match(regex).index).split('').reverse().join('');
}

let test = '||ab||cd||';
trimChar(test, '|');
console.log(test); //output: ab||cd

var str = '我的字符串在这里'; var index = str.match(/hre/).index; 警报(索引),<- 10

在现代浏览器中,您可以使用string.matchAll()来实现这一点。

与RegExp.exec()相比,这种方法的优点是它不依赖于正则表达式是有状态的,就像@Gumbo的答案中那样。

让regexp = /bar/g; 让STR = 'foobarfoobar'; let matches =[…str.matchAll(regexp)]; matches.forEach((match) => { Console.log ("match found at " + match.index); });