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

基于Manifest V3的Chrome扩展:URL章节号递增功能异常排查

问题分析

你的问题出在正则表达式的匹配逻辑上——当前代码尝试匹配URL中最后出现的数字串,但由于URL末尾的章节号后带有斜杠/,导致正则\d+$无法匹配到章节号6,反而误匹配了URL开头的长数字ID0907768668,最终造成错误的URL修改。

解决方案

修改正则表达式,专门定位到chapter-后的数字部分,确保只递增章节号:

修改后的popup.js代码

function analyzeUrl() {
  chrome.tabs.query({ active: true, lastFocusedWindow: true }, tabs => {
    let currentUrl = tabs[0].url;
    console.log('Analyzing URL:', currentUrl);
    // 匹配chapter-后面的数字,兼容数字后带斜杠或其他非数字字符的情况
    const chapterMatch = currentUrl.match(/chapter-(\d+)/);
    if (chapterMatch) {
      const chapterNum = parseInt(chapterMatch[1]);
      const newChapterNum = chapterNum + 1;
      // 精准替换对应的章节号部分
      const newUrl = currentUrl.replace(/chapter-(\d+)/, `chapter-${newChapterNum}`);
      console.log('Modified URL:', newUrl);
      chrome.tabs.update({ url: newUrl });
    } else {
      console.log('未找到符合格式的章节号');
    }
  });
}

console.log('starting....');
analyzeUrl();
console.log('end....');

代码说明

  • 使用/chapter-(\d+)/正则精准定位URL中chapter-后的数字,完全避免误匹配其他数字串
  • 替换操作仅针对章节号部分,保留URL其余内容不变
  • 增加未匹配到章节号的日志提示,方便调试排查
额外优化建议

如果需要兼容更多章节格式(比如chap-、ch-或大小写混用的情况),可以扩展正则:

// 匹配多种章节标识,忽略大小写
const chapterMatch = currentUrl.match(/(chapter|chap|ch)-(\d+)/i);
if (chapterMatch) {
  const chapterNum = parseInt(chapterMatch[2]);
  const newChapterNum = chapterNum + 1;
  // 保留原标识格式,替换数字部分
  const newUrl = currentUrl.replace(/(chapter|chap|ch)-(\d+)/i, `$1-${newChapterNum}`);
  chrome.tabs.update({ url: newUrl });
}

内容的提问来源于stack exchange,提问作者לידור תדלה

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 04:42:33