JasperZelf
JasperZelf

Reputation: 2844

extract number using regex

I have a string:

name:demo;morestuff.nbvideo:3;morestuff_here:45

from which I need to extract the nbvideo number. I managed it with 2 regexes, but I'm sure it can be done in just one regex.

Here's what I have now:

// get the nbvideo:XX part
videoPart = sink.tag.match(/nbvideo:([0-9]+)/gi);
// get the number from the video part
videoCount = videoPart[0].match(/([0-9]+)/gi)[0];

How can I extract the number behind 'nbvideo:' with one single regex?

Upvotes: 1

Views: 129

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

Remove g from the modifiers and access the first capture group value like this:

var sink_tag = "name:demo;morestuff.nbvideo:3;morestuff_here:45";
var m = sink_tag.match(/nbvideo:([0-9]+)/i);
if (m) {
   videoPart = m[1];
   document.body.innerHTML = videoPart; // demo
}

The thing is that string#match does not keep captures if a global modifier is used with a regex, and it seems you just have one nbvideo:<NUMBER> in the input. So, removing /g seems to be enough. Else, use RegExp#exec() in a loop.

Upvotes: 1

Related Questions