我試圖從正則表達式輸入youtube url來獲取視頻ID。無效的正則表達式 - 無法重複 - Javascript
下面是正則表達式我使用:
/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/
但它是回來爲
Uncaught SyntaxError: Invalid regular expression:
//^.*(youtu.be/|v/|u/w/|embed/|watch?v=|&v=|?v=)([^#&?]*).*//
: Nothing to repeat
爲什麼?
下面是我的代碼:
function PreviewVideo() {
var self = this;
this.links = $(".videoPreview");
this.bindEvents = function() {
self.links.on("click", self.fireModal);
};
this.getYoutubeId = function (url) {
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
return match[2];
} else {
return false;
}
};
this.fireModal = function (e) {
e.preventDefault;
var $this = $(this);
var videoField = $this.data("video");
var videoURL = $(videoField).val();
if (videoURL === "") {
$("body").append(UI.toast({level: "danger", time: 5000, html: "<h4>No video URL found</h4>", dismissable: true, position: "top-right"}));
} else {
var videoID = self.getYoutubeId(videoURL);
if (videoID) {
UI.modal({title: "Video preview", body: '<iframe width="560" height="315" src="//www.youtube.com/embed/' + videoID + '" frameborder="0" allowfullscreen></iframe>'})
} else {
$("body").append(UI.toast({level: "danger", time: 5000, html: "<h4>Invalid URL</h4>", dismissable: true, position: "top-right"}));
}
}
};
this.bindEvents();
}
的'/'youtube.be'被認爲是正則表達式結束後'。你必須逃避它。 –
@FabianKlötzl:它被逃脫了,代碼沒有正確標記。 –
可能重複[Javascript REGEX:如何從URL獲取YouTube視頻ID?](http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url ) –