Rooz Far
Rooz Far

Reputation: 187

Replacing youtube links with iframe in the html content?

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.

Upvotes: 1

Views: 1484

Answers (1)

Protozoid
Protozoid

Reputation: 1207

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 :)

Upvotes: 4

Related Questions