Node.js如何用正则判断输入URL是否匹配指定前缀列表
Node.js URL固定前缀匹配解决方案
更推荐的非正则实现(易维护、无正则转义坑)
你要匹配的是固定的已知前缀,不需要用到正则的复杂规则,直接用JS内置的startsWith方法实现即可,性能和可维护性都更高:
// 定义所有允许的URL前缀 const ALLOWED_PREFIXES = [ "https://open.spotify.com/playlist/", "https://www.youtube.com/watch", "https://youtu.be/", "https://open.spotify.com/track/", "https://youtube.com/playlist", ] /** * 匹配输入URL对应的前缀 * @param {string} inputUrl 用户输入的URL * @returns {string|undefined} 匹配到的前缀,未匹配返回undefined */ function matchUrlPrefix(inputUrl) { // 先标准化URL,去除首尾空格,避免无效字符干扰 const normalizedUrl = inputUrl.trim() // 遍历前缀列表查找第一个匹配的项 return ALLOWED_PREFIXES.find(prefix => normalizedUrl.startsWith(prefix)) }
使用示例
// 匹配spotify单曲链接 console.log(matchUrlPrefix("https://open.spotify.com/track/1vrd6UOGamcKNGnSHJQlSt?si=61680eaef0ac419e")) // 输出:https://open.spotify.com/track/ // 匹配youtu.be短链 console.log(matchUrlPrefix("https://youtu.be/5qap5aO4i9A")) // 输出:https://youtu.be/
正则实现方案
如果你有强制使用正则的需求,可以将所有前缀转义后拼接为正则表达式,避免特殊字符被误识别为正则元字符:
const ALLOWED_PREFIXES = [ "https://open.spotify.com/playlist/", "https://www.youtube.com/watch", "https://youtu.be/", "https://open.spotify.com/track/", "https://youtube.com/playlist", ] // 转义正则特殊字符 function escapeRegExp(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') } // 生成前缀匹配正则,^ 限定从开头匹配 const prefixReg = new RegExp(`^(${ALLOWED_PREFIXES.map(escapeRegExp).join('|')})`) function matchUrlPrefixWithReg(inputUrl) { const matchRes = inputUrl.trim().match(prefixReg) return matchRes ? matchRes[1] : undefined }
原有正则的问题
- 第一个正则仅能匹配youtube playlist场景,覆盖范围远小于你的需求,也无法返回匹配到的具体前缀
- 第二个正则匹配范围过宽,只要域名符合youtube/youtu.be规则的链接都会被命中,无法精准匹配你指定的前缀规则
内容的提问来源于stack exchange,提问作者Crispy
相关产品推荐
相关产品推荐

