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


当前回答

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

其他回答

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

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

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

console.log(matchIndices)

输出:[3,9]

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

来自developer.mozilla.org文档的String .match()方法:

返回的数组有一个额外的输入属性,该属性包含 被解析的原始字符串。此外,它还有一个索引 属性中匹配的从零开始的索引 字符串。

当处理一个非全局的正则表达式(即,在你的正则表达式上没有g标志)时,.match()返回的值有一个index属性…你要做的就是进入它。

var index = str.match(/regex/).index;

下面是一个例子,展示了它的工作原理:

Var STR = '我的字符串这里'; Var index = str.match(/here/).index; console.log(指数);// <- 10

我已经成功地测试了IE5。

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

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

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

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

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

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