user984003 user984003 - 2 months ago 19
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



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) {

The expected output should be 16.

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