通过JavaScript正则表达式验证SoundCloud URL

6

我有两个来自Soundcloud的URL链接,我想要获取在.com/(或).sc/之后的所有内容。我完全不懂正则表达式,但我可以使用JavaScript的match/replace方法。唯一的问题是http与https的区别。

https://soundcloud.com/ilyao/lyao-lj-mtx-and-lj-mtxs-hair

http://snd.sc/1cvgIjv

任何帮助都将不胜感激。
以下是我拥有的内容,不确定如何进行替换的https或者这是否是最佳方法来解决这个问题...
function getSoundCloudInfo(url){
    return url.replace("https://soundcloud.com/", "").replace("http://snd.sc/", "");
}

你能展示一下你尝试过的吗? - HamZa
1
@HamZa,我刚刚添加了我目前正在使用的内容。 - Brian Putt
4个回答

7
function getSoundCloudInfo(url){
  var regexp = /^https?:\/\/(soundcloud\.com|snd\.sc)\/(.*)$/;
  return url.match(regexp) && url.match(regexp)[2]
}

soundcloud.comsnd.sc中的点应该被转义,否则验证将通过类似于soundcloudscom的域名。 /^https?:\/\/(soundcloud\.com|snd\.sc)\/(.*)$/ - keeri
snd.sc已经不存在了。 - Joel Christophel

6

虽然有点晚了,但是...

别忘了:

  1. 移动版本(在http(s)://后面加上m.
  2. 可能有结尾斜杠
  3. 可以是httphttps,具体取决于是否使用SSL/TLS
  4. 可以有或没有www

因此,完整的正则表达式为:

^(https?:\/\/)?(www.)?(m\.)?soundcloud\.com\/[\w\-\.]+(\/)+[\w\-\.]+/?$


4
((https:\/\/)|(http:\/\/)|(www.)|(m\.)|(\s))+(soundcloud.com\/)+[a-zA-Z0-9\-\.]+(\/)+[a-zA-Z0-9\-\.]+    

1
const FULL_YOUTUBE_REG_EXP = /^(?:(https?):\/\/)?(?:(?:www|m)\.)?youtube\.com\/watch.*v=([a-zA-Z0-9_-]+)/
const SHORT_YOUTUBE_REG_EXP = /^(?:(https?):\/\/)?(?:(?:www|m)\.)?youtu\.be\/([a-zA-Z0-9_-]+)/
const VIMEO_REG_EXP = /^(?:(https?):\/\/)?(?:www\.)?vimeo\.com\/(\d+)/
const SOUNDCLOUD_REGEXP = /^(?:(https?):\/\/)?(?:(?:www|m)\.)?(soundcloud\.com|snd\.sc)\/(.*)$/

1
由于OP表示他们不完全知道如何使用正则表达式,因此进行一些解释/展示这些正则表达式的上下文可能会很有用。另外,我不确定为什么要显示YouTube和Vimeo的正则表达式... - M Z

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接