Carl Edwards
Carl Edwards

Reputation: 14464

Using Regex to parse a URI

I'm currently using Modenizr to determine what link to serve users based on their device of choice. So if they're using a mobile device I want to return a URI if not then just return a traditional URL.

URI: spotify:album:1jcYwZsN7JEve9xsq9BuUX

URL: https://open.spotify.com/album/1jcYwZsN7JEve9xsq9BuUX

Right now I'm using slice() to retrieve the last 22 characters of the URI. Though it works I'd like to parse the string via regex in the event that the URI exceeds the aforementioned character amount. What would be the best way to get the string of characters after the second colon of the URI?

$(".spotify").attr("href", function(index, value) {
  if (Modernizr.touch) {
    return value
  } else {
    return "https://open.spotify.com/album/" + value.slice(-22);
  }
});

Upvotes: 0

Views: 790

Answers (2)

Downgoat
Downgoat

Reputation: 14371

Regex is appropriate for this task because it is quite simple, here's the RegEx which supports as many : as there are and will still work

/[\w\:]*\:(\w+)/

How it works

[\w\:]* Will get all word characters (Letters, numbers, underscore) and colons

\: Will basically tell the previous thing to stop at a colon. Regex is by default greedy, that means it will get the last colon

(\w+) Will select all word characters and store it in a group so we can access it


Use this like:

var string = 'spotify:album:1jcYwZsN7JEve9xsq9BuUX',
    parseduri = string.match(/[\w\:]*\:(\w+)/)[1];

parseduri is the result


And then you can finally combine this:

var url = 'https://open.spotify.com/album/'+parseduri;

Upvotes: 0

Lumi Lu
Lumi Lu

Reputation: 3305

I would like something like this using split.

var url = 'spotify:album:1jcYwZsN7JEve9xsq9BuUX'.split(':');    
var part = url[url.length-1];
// alert(part);

return "https://open.spotify.com/album/" + part;

Upvotes: 1

Related Questions