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


当前回答

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

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

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

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

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

其他回答

我很幸运地使用了这个基于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

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

您可以使用String对象的搜索方法。这将只适用于第一个匹配,但在其他情况下将完成您所描述的工作。例如:

"How are you?".search(/are/);
// 4

这是我想到的:

//查找引用文本的开始和结束位置 //双引号或单引号,支持转义字符,如\" \' Var STR = "这是一个带引号的字符串,因为你可以'读'"; var型 = /'((?:\\.|[^'])*)'|"((?:\\.|[^"])*)"/ igm; While (match = pat .exec(str)) { console.log(匹配。index + ' ' + pat . lastindex); }