匹配URL
如果你想破坏url,你甚至需要覆盖短url并嵌入。
下面是一个有效的正则表达式:
(http(s|):|)\/\/(www\.|)yout(.*?)\/(embed\/|watch.*?v=|)([a-z_A-Z0-9\-]{11})
下面是一个测试:
Regex101
如果你想要ID,你需要第六个成员。下面是一个例子
jQuery("textarea[name*='youtube_url']").blur(function() {
var target = jQuery(this).val();
var regExp = /(http(s|):|)\/\/(www\.|)yout(.*?)\/(embed\/|watch.*?v=|)([a-z_A-Z0-9\-]{11})/i;
var match = target.match(regExp);
// No need to check if 11 chars, already did that in the Regex
var videoID = '';
if (match[6]) {
videoID = match[6];
}
console.log(videoID);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>
<textarea name="youtube_url"></textarea>
如果您想从视频中获取时间(如果是PASD),可以改进regex,如下所示:
(http(s|):|)\/\/(www\.|)yout(.*?)\/(embed\/|watch.*?v=|)([a-z_A-Z0-9\-]{11})(\?t=.*|)
在第7组中,你会找到时间。这将返回带有get参数的时间
?t=
如果需要,可以仅隔离数字:
(http(s|):|)\/\/(www\.|)yout(.*?)\/(embed\/|watch.*?v=|)([a-z_A-Z0-9\-]{11})(?:\?t=|)(\d+|)
url后匹配。
因为我第一次没有得到这个问题,下面是如何获得URL后的文本以及URL(视频ID)。
(http(s|):|)\/\/(www\.|)yout(.*?)\/(embed\/|watch.*?v=|)([a-z_A-Z0-9\-]{11})(?:\?t=|)(\d+|)([\S\s]*)
([\S\s]*)
将捕获url前后的任何内容,包括换行符:
jQuery("textarea[name*='youtube_url']").blur(function() {
var target = jQuery(this).val();
var regExp = /(http(s|):|)\/\/(www\.|)yout(.*?)\/(embed\/|watch.*?v=|)([a-z_A-Z0-9\-]{11})(?:\?t=|)(\d+|)([\S\s]*)/i;
var match = target.match(regExp);
// No need to check if 11 chars, already did that in the Regex
if (match[6]) {
var videoID = match[6];
}
console.log("Video ID:");
console.log(match[6]);
console.log("Video start time:");
console.log(match[7]);
console.log("After:");
console.log(match[8]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><strong>Example to try:</strong></p>
<p>https://youtu.be/xcJtL7QggTI?t=73 this a Sony 4k Video starts at 73s</p>
<textarea name="youtube_url"></textarea>