You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何匹配数组内指定前缀的链接并获取其链接与索引

实现指定前缀链接的匹配与位置获取

这问题我熟,我来给你一步步讲怎么用JavaScript实现这个需求!核心思路是遍历数组,解析每个链接的域名(或前缀),筛选出符合条件的链接并记录它们的索引位置。

单个前缀匹配的实现

先看你给出的示例,比如要匹配filerio.in的链接,我们可以用URL对象来准确解析链接的域名,避免直接字符串匹配可能出现的误判(比如链接路径里刚好包含目标前缀的情况)。

代码示例

const links = ["https://hil.to/744I35354M0","https://filerio.in/nr435345oy8veq","https://mirrorace.com/m/143538h","https://download.jheberg.net/9pv2rewt80f4","https://www.indishare.me/ys7dwhretewldm5","https://www85.zippyshare.com/v/lOtryrx7","https://www.sendspace.com/file/8345370j8","https://1fichier.com/?rpc2lrandomltgwmx"];

function matchLinksByDomain(linksArray, targetDomain) {
    // 生成首字母大写的键名(比如filerio.in → Filerio)
    const keyName = targetDomain.split('.')[0].charAt(0).toUpperCase() + targetDomain.split('.')[0].slice(1);
    const result = {
        [keyName]: [],
        array: []
    };

    linksArray.forEach((link, index) => {
        try {
            const url = new URL(link);
            // 匹配域名
            if (url.host === targetDomain) {
                result[keyName].push(link);
                result.array.push(index);
            }
        } catch (error) {
            // 处理无效URL的情况
            console.warn(`跳过无效链接: ${link}`);
        }
    });

    // 如果只有一个匹配项,把数组转为单个字符串(和你的示例格式一致)
    if (result[keyName].length === 1) {
        result[keyName] = result[keyName][0];
    }

    return result;
}

// 使用示例:匹配filerio.in的链接
const filerioMatch = matchLinksByDomain(links, 'filerio.in');
console.log(filerioMatch);
// 输出结果:{ Filerio: 'https://filerio.in/nr435345oy8veq', array: [1] }

代码解释

  1. URL对象解析:用new URL(link)解析每个链接,能准确获取域名(url.host),比直接字符串匹配更可靠。
  2. 遍历与筛选:遍历数组时,检查每个链接的域名是否等于目标前缀,符合条件就记录链接和索引。
  3. 格式适配:如果只有一个匹配结果,把数组转为单个字符串,和你期望的示例格式完全一致;如果有多个匹配,会保留数组形式,更灵活。
  4. 错误处理:用try-catch包裹URL解析,避免无效链接导致程序崩溃。

扩展:匹配包含路径的前缀

如果你的需求是匹配包含路径的前缀(比如www.google.com/abc这类),可以改用startsWith方法来判断:

function matchLinksByFullPrefix(linksArray, fullPrefix) {
    // 从前缀中提取域名生成键名
    const prefixUrl = new URL(fullPrefix);
    const keyName = prefixUrl.host.split('.')[0].charAt(0).toUpperCase() + prefixUrl.host.split('.')[0].slice(1);
    const result = {
        [keyName]: [],
        array: []
    };

    linksArray.forEach((link, index) => {
        if (link.startsWith(fullPrefix)) {
            result[keyName].push(link);
            result.array.push(index);
        }
    });

    if (result[keyName].length === 1) {
        result[keyName] = result[keyName][0];
    }

    return result;
}

// 使用示例:匹配以https://www.sendspace.com/file开头的链接
const sendspaceMatch = matchLinksByFullPrefix(links, 'https://www.sendspace.com/file');
console.log(sendspaceMatch);
// 输出结果:{ Sendspace: 'https://www.sendspace.com/file/8345370j8', array: [6] }

扩展:同时匹配多个前缀

如果需要一次性匹配多个前缀,可以写一个函数批量处理:

function matchMultipleDomains(linksArray, targetDomains) {
    const finalResult = {};

    targetDomains.forEach(domain => {
        const keyName = domain.split('.')[0].charAt(0).toUpperCase() + domain.split('.')[0].slice(1);
        finalResult[keyName] = {
            links: [],
            indices: []
        };

        linksArray.forEach((link, index) => {
            try {
                const url = new URL(link);
                if (url.host === domain) {
                    finalResult[keyName].links.push(link);
                    finalResult[keyName].indices.push(index);
                }
            } catch (error) {
                console.warn(`跳过无效链接: ${link}`);
            }
        });

        // 适配单个匹配项的格式
        if (finalResult[keyName].links.length === 1) {
            finalResult[keyName].link = finalResult[keyName].links[0];
            delete finalResult[keyName].links;
        }
    });

    return finalResult;
}

// 使用示例:同时匹配filerio.in和mirrorace.com
const multipleMatches = matchMultipleDomains(links, ['filerio.in', 'mirrorace.com']);
console.log(multipleMatches);
// 输出结果:
// {
//   Filerio: { link: 'https://filerio.in/nr435345oy8veq', indices: [1] },
//   Mirrorace: { link: 'https://mirrorace.com/m/143538h', indices: [2] }
// }

内容的提问来源于stack exchange,提问作者Malek GTX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:25:02