在Javascript中,如何获得正则表达式匹配的长度?
例如,如果字符串是
str = "/abc/hellothere/andmore/"
Run Code Online (Sandbox Code Playgroud)
正则表达式是
reg = new RegExp('/abc/[^/]*/');
Run Code Online (Sandbox Code Playgroud)
然后我想要16,长度
/abc/hellothere/
Run Code Online (Sandbox Code Playgroud)
假设您确实希望正则表达式匹配您的示例输入:
var str = '/abc/hellothere/andmore/';
var reg = new RegExp('/abc/[^/]*/');
var matches = str.match(reg);
if (matches && matches.length) {
console.log(matches[0].length);
}Run Code Online (Sandbox Code Playgroud)
预期的产出应该是16.
请参阅String.prototype.match和RegExp.prototype.exec.