opticon
opticon

Reputation: 3614

Simple Nodejs Regex: Extract text from between two strings

I'm trying to extract the Vine ID from the following URL:

https://vine.co/v/Mipm1LMKVqJ/embed

I'm using this regex:

/v/(.*)/

and testing it here: http://regexpal.com/

...but it's matching the V and closing "/". How can I just get "Mipm1LMKVqJ", and what would be the cleanest way to do this in Node?

Upvotes: 11

Views: 42216

Answers (1)

hwnd
hwnd

Reputation: 70732

You need to reference the first match group in order to print the match result only.

var re = new RegExp('/v/(.*)/');
var r  = 'https://vine.co/v/Mipm1LMKVqJ/embed'.match(re);
if (r)
    console.log(r[1]); //=> "Mipm1LMKVqJ"

Note: If the url often change, I recommend using *? to prevent greediness in your match.

Although from the following url, maybe consider splitting.

var r = 'https://vine.co/v/Mipm1LMKVqJ/embed'.split('/')[4]
console.log(r); //=> "Mipm1LMKVqJ"

Upvotes: 17

Related Questions