Last active
November 26, 2021 21:29
-
-
Save jphase/9086823 to your computer and use it in GitHub Desktop.
Regex match all youtube links
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
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
Thanks a ton!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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>