lopata
lopata

Reputation: 1365

regex javascript doesn't return parenthesis

When I am trying to do my regex in js:

var matc = source.match(/sometext(\d+)/g);

The result I get is "sometext5615", "sometext5616"...etc But what I want: is to get "5615", "5616"...etc

Do you have any idea how to get only what is inside the parenthese ?

Upvotes: 2

Views: 110

Answers (2)

Oriol
Oriol

Reputation: 287990

String.prototype.match has two different behaviors:

  • If the regex doesn't have the global g flag, it returns regex.exec(str). That means that, if there is a match, you will get an array where the 0 key is the match, the key 1 is the first capture group, the 2 key is the second capture group, and so on.

  • If the regex has the global g flag, it returns am array with all matches, but without the capturing groups.

Therefore, if you didn't use the global flag g, you could use the following to get the first capture group

var matc = (source.match(/sometext(\d+)/) || [])[1];

However, since you use the global flag, you must iterate all matches manually:

var rg = /sometext(\d+)/g,
    match;
while(match = rg.exec(source)) {
    match[1]; // Do something with it, e.g. push it to an array
}

Upvotes: 4

Explosion Pills
Explosion Pills

Reputation: 191729

JavaScript does not have a "match all" for global matches, so you cannot use g in this context and also have capture groups. The simplest solution would be to remove the g and then just use matc[1] to get 5615, etc.

If you need to match multiple of these within the same string then your best bet would be to do a "search and don't replace"

var matc = [];
source.replace(/sometext(\d+)/g, function (_, num) {
    matc.push(num);
});

Upvotes: 1

Related Questions