繁体   English   中英

如何从字符串中减去和保留前导零

[英]How to subtract and retain leading zeros from a string

我必须从字符串PR001-CC001578中减去 -1 并将其作为参数传递给xpath以识别元素。 我用CC拆分它并从001578中减去 -1 。 结果是1577 但前导零被删除,因为xpath识别失败。

        let courseID = "PR001-CC001578";
        let currCourseID = courseID.split('CC');
        let otherCourseID = currCourseID[1]-1;
        console.info("other Course ID:", otherCourseID);
        var courseIDAssetsPg="//div[contains(text(),'%d')]";
        var replaceCCId = courseIDAssetsPg.replace("%d", otherCourseID);
        var CCIdLoc = element(by.xpath(replaceCCId));
        console.info("locator: ", CCIdLoc )

output:

other Course ID: 1577  //missing 0's here
locator : //div[contains(text(),'1577')]

请让我知道是否有其他方法可以处理此问题。 我希望定位器是//div[contains(text(),'PR001-001577')]

提前致谢 !

我想另一种方法是使用这种方法将 id 分为两部分,以这种方式更改数字并根据 6 位格式恢复结果编号:

 let courseID = "PR001-CC001578"; const parts = courseID.split('-'); const lastNumber = parts[1].replace(/\D/g, "") - 1; const formattedLastNumber = `${lastNumber}`.padStart(6, '0'); console.log(formattedLastNumber);

作为中间步骤,您可以使用正则表达式查找并提取前导零,将它们保存到附加变量(可选)中,并在您进行数学运算后将它们添加到新数字中。

但是,您必须考虑在数学运算后前导零的数量发生变化的特殊情况(例如,1000-1=999)。

let courseID = "PR001-CC001578";
let currCourseID = courseID.split('CC');
let leadingZeros = currCourseID[1].match(/^0*/); // changed this
let otherCourseID = leadingZeros + (currCourseID[1] - 1); // and changed this
if (otherCourseID.length < currCourseID[1].length) {
    otherCourseID = "0" + otherCourseID;
}
console.info("other Course ID:", otherCourseID);
var courseIDAssetsPg="//div[contains(text(),'%d')]";
var replaceCCId = courseIDAssetsPg.replace("%d", otherCourseID);
var CCIdLoc = element(by.xpath(replaceCCId));
console.info("locator: ", CCIdLoc )

或者,您可以简单地用适当数量的前导零填充数字:

const numZeros = currCourseID[1].length - otherCourseID.toString().length;
otherCourseID = "0".repeat(numZeros) + otherCourseID;

我认为用 RegEx 解析数字是最简单的,根据需要使用该数字(加或减 1),然后通过添加足够的前导零来组装一个新的 6 位数字,然后将其插入到您的字符串中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM