使用 Regex 解析 URI

Using Regex to parse a URI

我目前正在使用 Modenizr 来确定 link 根据用户选择的设备为用户提供什么服务。因此,如果他们使用的是移动设备,我想 return 一个 URI,如果不是,那么只是 return 一个传统的 URL.

URI: spotify:album:1jcYwZsN7JEve9xsq9BuUX

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

现在我正在使用 slice() 来检索 URI 的最后 22 个字符。虽然它有效,但我想在 URI 超过上述字符数量的情况下通过正则表达式解析字符串。获取 URI 第二个冒号后的字符串的最佳方法是什么?

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

我想要使用 split 这样的东西。

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

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

正则表达式非常适合这项任务,因为它非常简单,这里的正则表达式支持尽可能多的 : 并且仍然可以工作

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

工作原理

[\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


像这样使用:

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

parseduri是结果


然后你终于可以结合这个了:

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