如何从HTML的iframe文件路径中提取项目名称和对应版本号
实现方法
你可以通过JavaScript直接在浏览器环境中实现提取,核心逻辑是提取iframe的src路径、定位项目版本段、替换字符格式三步,以下是两种常用实现方案:
方案1:路径拆分法(逻辑直观,不需要写正则)
// 1. 获取目标iframe元素 const targetIframe = document.querySelector('iframe[name="docu"]'); // 2. 拆分src路径,过滤空路径段 const pathSegs = targetIframe.src.split('/').filter(seg => seg); // 3. 取倒数第二个路径段(即index.html的上级目录名) const projectVerSeg = pathSegs[pathSegs.length - 2]; // 4. 替换下划线为空格,外层加双引号 const finalResult = `"${projectVerSeg.replace('_', ' ')}"`; console.log(finalResult); // 输出:"PROJECT V1"
方案2:正则匹配法(代码更简洁,适合固定路径结构场景)
const targetIframe = document.querySelector('iframe[name="docu"]'); // 直接匹配src末尾 /xxx/index.html 中间的xxx部分 const matchRes = targetIframe.src.match(/\/([^/]+)\/index\.html$/); const finalResult = matchRes ? `"${matchRes[1].replace('_', ' ')}"` : ''; console.log(finalResult); // 输出:"PROJECT V1"
如果你的路径结构固定为/content/subpages/[项目名_版本号]/index.html,可以把正则写得更精准避免匹配异常:/\/content\/subpages\/([^/]+)\/index\.html$/
内容的提问来源于stack exchange,提问作者user17356872
相关产品推荐
相关产品推荐

