我想验证字符串是否为spotify或youtube或无效的URL。这有效,但似乎可以做得更简单。我怎样才能提高效率呢?
String.prototype.spotifyUrl = function() {
return this.match(/^(spotify:|https:\/\/[a-z]+\.spotify\.com\/)/);
}
String.prototype.youtubeUrl = function() {
return this.match(/^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/);
}
function validateUrl (url) {
if ( url.spotifyUrl() ) {
alert('spotify');
}
else if ( url.youtubeUrl() ) {
alert('youtube');
}
else {
alert('invalid url');
}
};
validateUrl('https://open.spotify.com/track/3JiockjOTd8m2VGcTGkmew');