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

如何通过正则生成参数化URL,保留数字前缀适配补零等通用场景

解决方案

现有代码的核心问题是直接将整段连续数字统一替换为%d,导致前导零被一并替换丢失。你可以通过分情况处理数字匹配结果解决该问题:

  1. 无前置零的数字串(如1、233)直接全量替换为%d
  2. 带前置零的数字串(如0001、00123)保留所有前置零,仅将后续数字部分替换为%d

修改后的完整代码如下:

function checkIfUniqueURL(url) {
    const urlArr = url.split("/");
    const lastSegment = urlArr[urlArr.length - 1];
    // 处理最后一段路径中的数字
    const processedSegment = lastSegment.replace(/\d+/g, (match) => {
        // 判断是否为带前导零的数字串
        if (/^0+\d+$/.test(match)) {
            // 保留前导零,后续数字替换为%d
            return match.replace(/^(0+)\d+$/, '$1%d');
        }
        // 无前导零直接替换为%d
        return '%d';
    });
    const result = url.substr(0, url.lastIndexOf("/") + 1) + processedSegment;
    console.log(result);
    return result;
}

测试验证

你可以用以下用例验证效果:

checkIfUniqueURL("https://www.example.com/1"); 
// 输出:https://www.example.com/%d
checkIfUniqueURL("https://www.example.com/0001"); 
// 输出:https://www.example.com/000%d
checkIfUniqueURL("https://www.example.com/json1.json"); 
// 输出:https://www.example.com/json%d.json
checkIfUniqueURL("https://www.example.com/00456.json"); 
// 输出:https://www.example.com/00%d.json

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:45:00