如何在Cypress中提取文本里"of"之后的末尾数字?
Cypress提取指定位置数字的解决方案
针对你需要从文本“1-44 of 44”中提取“of”之后末尾数字的需求,这里提供两种精准的实现方法:
方法1:使用正则捕获组匹配
直接通过正则定位“of ”后的数字,确保只提取目标值:
cy.get(':nth-child(3) > span').invoke('text') .then((text) => { // 匹配"of "后面的连续数字,捕获组1即为目标数字 const match = text.match(/of (\d+)/); if (match) { const targetNum = parseInt(match[1], 10); console.log('提取到的数字:', targetNum); // 将结果存为Cypress别名,方便后续步骤调用 cy.wrap(targetNum).as('totalItems'); } });
方法2:字符串分割处理
通过分割字符串直接获取“of ”之后的部分,再转换为数字:
cy.get(':nth-child(3) > span').invoke('text') .then((text) => { // 按"of "分割字符串,取后半段并去除多余空格 const targetStr = text.split('of ')[1]?.trim(); if (targetStr) { const targetNum = parseInt(targetStr, 10); console.log('提取到的数字:', targetNum); cy.wrap(targetNum).as('totalItems'); } });
原代码问题说明
你之前使用的/[0-9]+/g正则会匹配文本中所有数字片段,因此得到["1","44","44"]的结果,无法直接定位到“of”后的目标数字。上述两种方法都能精准锁定目标位置的数字,避免无关匹配。
内容的提问来源于stack exchange,提问作者Michelle Murray
相关产品推荐
相关产品推荐

