Ad

Check If String Is Spotify URL

- 1 answer

I need to create a function to check if a string is a Spotify URL. I made a simple if statement to check if the string contains part of the Spotify URL, it works, but it's crap. Can somebody show me better approach with Regex or something else.

if ( input.indexOf('spotify:') > -1  || input.indexOf('spotify.com')  > -1) {
    console.log('url');
}

Spotify URLs come in these three forms:

https://play.spotify.com/user/spotifydiscover/playlist/0vL3R9wDeAwmXTTuRATa14
https://open.spotify.com/track/1TZ3z6TBztuY0TLUlJZ8R7
spotify:track:1TZ3z6TBztuY0TLUlJZ8R7
Ad

Answer

/^(spotify:|https://[a-z]+\.spotify\.com/)/

http://www.regexr.com/3cl88

With proper JS escaping, as there's quite some slashes in there:

var url = 'https://open.spotify.com/track/1TZ3z6TBztuY0TLUlJZ8R7';
console.log(/^(spotify:|https:\/\/[a-z]+\.spotify\.com\/)/.test(url));
// Outputs 'true'
Ad
source: stackoverflow.com
Ad