1

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?

4
  • Just use the capturing group in the first regex. Commented Feb 19, 2016 at 10:21
  • 2
    Remove g from the modifiers and access it via index 1. sink.tag.match(/nbvideo:([0-9]+)/i)[1] (add error checking of course) Commented Feb 19, 2016 at 10:21
  • thanks @WiktorStribiżew.... works like a charm Commented Feb 19, 2016 at 10:25
  • that wont help. If you are using indexes then you can use string split by .nbvideo: and use index to get first character. But will the number be only a single digit is the point. Commented Feb 19, 2016 at 10:36

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.