Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, get length of matching regular expression

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/
like image 335
user984003 Avatar asked Mar 11 '23 19:03

user984003


1 Answers

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.

like image 85
André Dion Avatar answered Mar 23 '23 07:03

André Dion