我需要创建一个函数来检查字符串是否是Spotify URL。我做了一个简单的if语句来检查字符串是否包含Spotify URL的一部分,它可以工作,但它是废话。有人可以用Regex或其他东西向我展示更好的方法。
if ( input.indexOf('spotify:') > -1 || input.indexOf('spotify.com') > -1) {
console.log('url');
}
Spotify网址有以下三种形式:
https://play.spotify.com/user/spotifydiscover/playlist/0vL3R9wDeAwmXTTuRATa14
https://open.spotify.com/track/1TZ3z6TBztuY0TLUlJZ8R7
spotify:track:1TZ3z6TBztuY0TLUlJZ8R7
答案 0 :(得分:6)
/^(spotify:|https://[a-z]+\.spotify\.com/)/
正确的JS转义,因为那里有很多斜杠:
var url = 'https://open.spotify.com/track/1TZ3z6TBztuY0TLUlJZ8R7';
console.log(/^(spotify:|https:\/\/[a-z]+\.spotify\.com\/)/.test(url));
// Outputs 'true'
答案 1 :(得分:2)
匹配
var input = 'https://play.spotify.com/user/spotifydiscover/playlist/0vL3R9wDeAwmXTTuRATa14';
if(/\.spotify\.com/.test(input))
{
// contains spotify
}
答案 2 :(得分:1)
要测试网址是以open
开头,还是play
使用:
> var url = 'https://play.spotify.com/user/spotifydiscover/playlist/0vL3R9wDeAwmXTTuRATa14';
> var re = /((open|play)\.spotify\.com\/)/;
> console.log(re.test(url));
< true
使用match()
您可以检索网址的格式。
> console.log(url.match(re));
< ["play.spotify.com/", "play.spotify.com/", "play"]
或者:
> console.log(url.match(re)[2]);
< "play"
答案 3 :(得分:0)
如果有人想验证Spotify字符串,获取ID以及它是曲目还是专辑,请使用以下表达式:
const str = "https://open.spotify.com/album/0BwWUstDMUbgq2NYONRqlu?si=5qGtCb3_Qh2SburnU09NtQ";
const regEx = /^(?:spotify:|(?:https?:\/\/(?:open|play)\.spotify\.com\/))(?:embed)?\/?(album|track)(?::|\/)((?:[0-9a-zA-Z]){22})/;
const match = str.match(regEx);
if(match){
const albumOrTrack = match[1]
const spotifyID = match[2]
//albumOrTrack: album
//spotifyID: 0BwWUstDMUbgq2NYONRqlu
}
这将匹配Spotify链接,来自嵌入代码的Spotify链接以及Spotify URI。有关正则表达式工作原理的说明,请将其粘贴到https://www.regex101.com