GardenTools & experiments

Reading a JavaScript regex capture group

The difference between a full match and the substring captured between two delimiters.

A regex match can return both the complete match and the text captured by parentheses. The original example placed one capture group between a and j:

var source = "afskfsd33j"
var result = source.match(/a(.*)j/);

result: ["afskfsd33j", "fskfsd33"]

The first array element is the full matched text; the next is the group matched by (.*). The result: line is recorded output, not another JavaScript statement.

.* is greedy, so a longer input with several possible ending delimiters can capture more than a simple example suggests. A nonmatching input returns no match, which callers must handle before indexing the result.

← Back to the garden