如何在Cypress中提取并存储URL的末尾字符串
提取URL末尾数字并存储为全局变量
从URL https://www.xxx/xxxx/xxx/1234 中提取末尾的数字1234并存储到全局变量,你可以基于现有代码修改,实现方式如下:
基础实现(基于原代码逻辑)
直接在提取后将值存入全局变量,以Cypress环境变量或window全局对象为例:
// 提取URL最后一段的数字 const targetNumber = this.href.substring(this.href.lastIndexOf('/') + 1); // 方式1:存入Cypress全局环境变量 Cypress.env('extractedNumber', targetNumber); // 方式2:挂载到window对象作为全局变量 window.extractedNumber = targetNumber; // 打印验证结果 cy.log(targetNumber);
更严谨的正则匹配(适配末尾可能有非数字的情况)
如果URL末尾可能包含非数字字符,用正则精准匹配数字部分更可靠:
const numberMatch = this.href.match(/(\d+)$/); if (numberMatch) { const targetNumber = numberMatch[1]; // 存入全局变量 Cypress.env('extractedNumber', targetNumber); cy.log(targetNumber); }
内容的提问来源于stack exchange,提问作者David Pongo
相关产品推荐
相关产品推荐

