最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - In Javascript, get length of matching regular expression - Stack Overflow

programmeradmin0浏览0评论

In Javascript, how do I get the length of the regex match?

For example, if the string is

str = "/abc/hellothere/andmore/"

And the regexp is

reg = new RegExp('/abc/[^/]*/');

Then I want 16, the length of

/abc/hellothere/

In Javascript, how do I get the length of the regex match?

For example, if the string is

str = "/abc/hellothere/andmore/"

And the regexp is

reg = new RegExp('/abc/[^/]*/');

Then I want 16, the length of

/abc/hellothere/
Share Improve this question edited Oct 29, 2016 at 22:47 user984003 asked Oct 29, 2016 at 22:40 user984003user984003 29.6k69 gold badges202 silver badges315 bronze badges 2
  • Are you sure that regex matches your string? – adeneo Commented Oct 29, 2016 at 22:42
  • Yes, now. Added a "/" to front of str. – user984003 Commented Oct 29, 2016 at 22:45
Add a ment  | 

1 Answer 1

Reset to default 11

Assuming you actually want your regex to match your sample input:

var str = '/abc/hellothere/andmore/';
var reg = new RegExp('/abc/[^/]*/');
var matches = str.match(reg);

if (matches && matches.length) {
  console.log(matches[0].length);
}

The expected output should be 16.

Refer to String.prototype.match and RegExp.prototype.exec.

发布评论

评论列表(0)

  1. 暂无评论