1

I have a javascript code that searches in a html page/content and replaces every youtube link with an iframe embedded link.

This works fine for normal youtube links like this:

https://www.youtube.com/watch?v=2xZL3WoBQzI

However, some of the video links in my html have an extra variable at the end of them which causes my JavaScript code to not work properly.

They are like this:

https://www.youtube.com/watch?v=2xZL3WoBQzI&t=15s

The issue is because of the &t=15s

This is my code:

$('.element').html(function(i, html) {

return html.replace(/(?:https:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, '<iframe width="100%" src="https://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>');

});

Could someone please advice on this issue?

Thanks in advance.

Rooz Far
  • 187
  • 1
  • 3
  • 11

1 Answers1

4

You could adjust the regex to only look for word characters that come after the v=.

Your new regex would look like this: /(?:https:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?.*v=)?(\w+)/g

The last bit changed from: (?:watch\?v=)?(.+) to (?:watch\?.*v=)?(\w+)

So your new code would look like:

$('.element').html(function(i, html) {

return html.replace(/(?:https:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?.*v=)?(\w+)/g, '<iframe width="100%" src="https://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>');

});

EDIT: Dang it! As you can tell, coming up with the right regex takes time, so perhaps you should re-use the regex suggested here: Regular expression for youtube links

Hope this does the job :)

Protozoid
  • 1,207
  • 1
  • 8
  • 16
  • This breaks the code for normal YouTube links without the &t=15s – Rooz Far May 30 '18 at 10:35
  • Oups, forgot to add ? after the non-capturing group `(?:&)?` Edited comment. – Protozoid May 30 '18 at 10:38
  • Now, it works with the normal links again but not for the links with the &t=15s variable. – Rooz Far May 30 '18 at 10:41
  • Completely edited the reply with a solution that works for both and doesn't place a dependency on the order of the URL params – Protozoid May 30 '18 at 10:45
  • sorry but still not working! some of the youtube links in the html content look like this: https://youtu.be/Gx-x7_htyddf. my own code works fine with these links but with your code seems to ignore them as a valid youtube link and it doesn't create the iFrame for them! – Rooz Far May 30 '18 at 11:02
  • Dang it, you're right ... how about the regex suggested here https://stackoverflow.com/questions/3717115/regular-expression-for-youtube-links ? – Protozoid May 30 '18 at 11:45
  • nice find. this regex seems to work fine: http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)? – Rooz Far May 30 '18 at 11:55
  • @RoozFar I'm glad things worked out :) Can you please close the question if it's been answered? – Protozoid Jun 01 '18 at 11:26