Skip to content

Instantly share code, notes, and snippets.

@jphase
Last active November 26, 2021 21:29
Show Gist options
  • Save jphase/9086823 to your computer and use it in GitHub Desktop.
Save jphase/9086823 to your computer and use it in GitHub Desktop.
Regex match all youtube links
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<div id="anothercontainer">
<div>not me</div>
<div>there's something http://www.youtube.com/watch?v=_-lT1oOU7b4 here</div>
<div>but not here</div>
<ul>
<li>this has "has" in it</li>
<li>some text https://youtu.be/_-lT1oOU7b4</li>
<li>has this one?</li>
<li>not this one</li>
</ul>
</div>
<hr>Stuff below here is ignore because it's not in #anothercontainer<hr>
<div id="container">
<div>even though there's a has, it will only work with #anothercontainer</div>
<ul>
<li>has</li>
<li>don't have</li>
</ul>
</div>
<script>
$(function() {
// Return all youtube links from text content
function youtubelinks(parent, children) {
// Initialize
var results = [];
// Loop through youtube regular expressions array
$.each($(parent).find(children), function(index, value) {
// Match elements containg youtube urls
var match = $(this).text().match(/(http:|https:)?\/\/(www\.)?(youtube.com|youtu.be)\/(watch)?(\?v=)?(\S+)?/);
if(match != null) {
// Add matched URL to results
results.push(match);
}
});
// Return our links
return results;
}
// Get results example usage
var ytlinks = youtubelinks('#anothercontainer', 'div, li');
$.each(ytlinks, function(index, value) {
console.log(value[0]);
});
});
</script>
</body>
</html>
@ZephiroRB
Copy link

No work with two links example:

<div>there's something http://www.youtube.com/watch?v=_-lT1oOU7b4 here http://www.youtube.com/watch?v=_-lT1oOU7b4</div>

@ardenn
Copy link

ardenn commented Jul 24, 2018

Thanks for this. Here is a tiny bit of modification to the regex string to match even embed links, and links without the protocol, and some misspelt links
.match(/(http:|https:)?(\/\/)?(www\.)?(youtube.com|youtu.be)\/(watch|embed)?(\?v=|\/)?(\S+)?/);

This matches:
http:youtu.be/4fHwJMaOF8Q (misspelt)
youtu.be/4fHwJMaOF8Q (no protocol)
https://youtu.be/4fHwJMaOF8Q
youtube.com/embed/4fHwJMaOF8Q and
https://www.youtube.com/embed/4fHwJMaOF8Q

@rojvv
Copy link

rojvv commented Jul 28, 2021

Thanks a ton!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment