-1

I want to get only youtube id from the following url

https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0

 $(".youtube").click(function () {
       console.log(this.href.replace(new RegExp("embed\\/", "i"), 'embed/'));

 });

This gets me the whole url while i want to get only YouTubeID cqyziA30whE when ever user click on any of the links

Learning
  • 19,469
  • 39
  • 180
  • 373
  • I closed this question as a dupe of a famous old one. If that didn't answer your question please edit accordingly. – revo Sep 17 '18 at 05:58

4 Answers4

2

Capture non-question mark characters following /embed/ in a group, then use that captured group:

const str = 'https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0';
console.log(
  str.match(/\/embed\/([^?]+)/)[1]
);

You could also lazy-repeat any character until you get to a question mark:

const str = 'https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0';
console.log(
  str.match(/\/embed\/(.+)\?/)[1]
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

Split() the string with \ separator and then split() the result with seperator ? and the desired result is the first element of splitted array..

var string = "https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0";
var words=string.split('/');
console.log(words[4].split('?')[0]);
chintuyadavsara
  • 1,509
  • 1
  • 12
  • 23
1

You can use RegEx groups and capture it.

var url = 'https://www.youtube.com/embed/nrGk0AuFd_9?controls=1&showinfo=0&rel=0&autoplay=0&loop=0';
console.log(url.replace(new RegExp("^.*\/embed\/([a-zA-Z0-9_-]+)\?.*", "i"), '$1'));
rrk
  • 15,677
  • 4
  • 29
  • 45
  • You are validating it for only basic characters what if it has other characters? Example `https://www.youtube.com/watch?v=nrGk0AuFd_9` this has `_` – Learning Sep 17 '18 at 05:57
  • @Learning Well you could just add the characters `-` and `_` to the regex. YouTube video id's allows only these characters other than `[a-zA-Z0-9]`. So final `[a-zA-Z0-9_-]`. – rrk Sep 17 '18 at 07:17
0

If you want a smart way to avoid RegExp you can use HTMLHyperlinkElementUtils.pathname like this:

const href = 'https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0'
const a = document.createElement('a')

a.href = href

const id = a.pathname.split('/').pop()

console.log(id)

Based on your snippet you might be able to do something as simple as this:

$(".youtube").click(function() {
  console.log(this.pathname.split('/').pop());
});
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153