Simple Nodejs Regex: Extract text from between two strings

22,788

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"
Share:
22,788
opticon
Author by

opticon

Updated on July 09, 2022

Comments

  • opticon
    opticon almost 2 years

    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?