I need to extract the playlist id from a spotify link. The link could come in two forms:
https://open.spotify.com/playlist/1GXN1gZMuTlW5LjpTNJF2q
https://open.spotify.com/playlist/1GXN1gZMuTlW5LjpTNJF2q?si=d3fa4293e26049f8
expected result => 1GXN1gZMuTlW5LjpTNJF2q
I've tried (?<=\/playlist\/)(.*)(?=\?|$)
to match between /playlist/ and the end or a question mark, but can't seem to get it to work.
CodePudding user response:
You can use URL interface to get the path.
new URL(uri).pathname.split('/').pop()
const uri = 'https://open.spotify.com/playlist/1GXN1gZMuTlW5LjpTNJF2q?si=d3fa4293e26049f8';
console.log(new URL(uri).pathname.split('/').pop());
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Your pattern should use a non greedy quantifier (?<=\/playlist\/).*?(?=\?|$)
but in this case you don't need any lookarounds at all. You can use a capture group instead with a negated character class matching any character except for ?
If you want to match spotify links only, you can make the pattern more specific
\bhttps?:\/\/[^/]*\bspotify\.com\/playlist\/([^\s?] )
Or only for open.spotify
\bhttps?:\/\/open.spotify\.com\/playlist\/([^\s?] )
const regex = /\bhttps?:\/\/[^/]*\bspotify\.com\/playlist\/([^\s?] )/;
[
"https://open.spotify.com/playlist/1GXN1gZMuTlW5LjpTNJF2q",
"https://open.spotify.com/playlist/1GXN1gZMuTlW5LjpTNJF2q?si=d3fa4293e26049f8"
].forEach(s => {
const m = s.match(regex);
if (m) {
console.log(m[1])
}
});
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>