user984003 user984003 - 1 month ago 11
Javascript Question

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/

Answer

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.

Comments