Pete
Pete

Reputation: 3451

RegEx for matching YouTube embed ID

I'm in non-modern JavaScript and I have a string defined as follows:

"//www.youtube.com/embed/DmYK479EpQc?vq=hd720&rel=0"

I want to pull out just the DmYK479EpQc but I don't know the length. I do know that I want what is after the / and before the ?

Is there some simple lines of JavaScript that would solve this?

Upvotes: 0

Views: 222

Answers (6)

Teocci
Teocci

Reputation: 8835

You can use this regex

.* match and consume everything up to [A-z0-9]+ then match and capture any number and character between A-z .* then consume the rest of the input

const ytUrl = '//www.youtube.com/embed/DmYK479EpQc?vq=hd720&rel=0';
const regex = /(.*)(d\/)([A-z0-9]+)(\?)(.*)/gm;
const position = '$3';

let result = ytUrl.replace(regex, position);

console.log('YouTube ID: ', result);

This regex just split the string into different sections and the YouTube id is at the 3rd position.

Another, solution is using split. This method splits a string into an array of substrings.

const ytUrl = '//www.youtube.com/embed/DmYK479EpQc?vq=hd720&rel=0';

let result = ytUrl.split('/').pop().split('?').shift()

console.log('YouTube ID: ', result);

In this sample, we split the URL using / as separator. Then we took the last element of the array with the pop method. and finally we split again using ? as separator and we take the first element of the array with the shift method.

Upvotes: 0

user128511
user128511

Reputation:

Use the URL object?

console.log(
   (new URL("//www.youtube.com/embed/DmYK479EpQc?vq=hd720&rel=0", location.href)).pathname
   .split('/')
   .pop());

Why? Because I can likely make up a URL that defeats the regex (though for youtube it's probably unlikely)

Upvotes: 2

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

How about non-regex way

console.log("//www.youtube.com/embed/DmYK479EpQc?vq=hd720&rel=0".split('/').pop().split('?')[0]);

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

One option uses a regex replacement:

var url = "//www.youtube.com/embed/DmYK479EpQc?vq=hd720&rel=0";
var path = url.replace(/.*\/([^?]+).*/, "$1");
console.log(path);

The above regex pattern says to:

.*       match and consume everything up to and
/        including the last path separator
([^?]+)  then match and capture any number of non ? characters
.*       then consume the rest of the input

Then, we just replace with the first capture group, which corresponds to the text after the final path separator, but before the start of the query string, should the URL have one.

Upvotes: 0

Pablo Navarro
Pablo Navarro

Reputation: 452

I'm not going to give a piece of code because this is a relatively simple algorithm, and easy to implement.

Please note that those links has this format (correct me if I'm wrong):

  • https:// or http://
  • www.youtube.com/
  • embed/
  • Video ID (DmYK479EpQc in this case)
  • ?parameters (note that they start ALWAYS with the character ?)

You want the ID of the video, so you can split the string into those sections and if you store those sections in one array you can be sure that the ID is at the 3rd position.

One example of how that array would look like would be:

['https://', 'www.youtube.com', 'embed', 'DmYK479EpQc', '?vq=hd720&rel=0']

Upvotes: 0

Emma
Emma

Reputation: 27723

This expression might help you to do so, and it might be faster:

(d\/)([A-z0-9]+)(\?)

enter image description here

Graph

This graph shows how the expression would work and you can visualize other expressions in this link:

enter image description here

const regex = /(.*)(d\/)([A-z0-9]+)(\?)(.*)/gm;
const str = `//www.youtube.com/embed/DmYK479EpQc?vq=hd720&rel=0`;
const subst = `$3`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

Performance Test

This JavaScript snippet shows the performance of that expression using a simple 1-million times for loop.

const repeat = 1000000;
const start = Date.now();

for (var i = repeat; i >= 0; i--) {
	const string = '//www.youtube.com/embed/DmYK479EpQc?vq=hd720&rel=0';
	const regex = /(.*)(d\/)([A-z0-9]+)(\?)(.*)/gm;
	var match = string.replace(regex, "$3");
}

const end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match 💚💚💚 ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");

Upvotes: 1

Related Questions