【问题标题】:How to subtract and retain leading zeros from a string如何从字符串中减去和保留前导零
【发布时间】:2022-01-03 11:24:22
【问题描述】:

我必须从字符串 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 )

输出:

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

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

提前致谢!

【问题讨论】:

  • 您不能保留前导零,您必须将数字结果再次转换为字符串,并添加前导零。见developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 作为中间步骤,您可以先提取前导零并将其保存在变量中,然后再将其解析为数字。
  • '00' + (currCourseID[1] - 1)你可以这样更新。
  • @Bansi29 当id超过9时你的代码会失败。
  • 参考我的第一条评论,可以let otherCourseID = (currCourseID[1] - 1).toString().padStart(6, '0');

标签: javascript java selenium


【解决方案1】:

我想另一种方法是使用这种方法,将 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);

【讨论】:

    【解决方案2】:

    作为中间步骤,您可以使用regular expressions 查找前导零并使用extract 将它们保存到一个附加变量(可选)中,并在您进行数学运算后将它们添加到新数字中。

    但是,您必须考虑在数学运算后前导零的数量发生变化的特殊情况(例如,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 )
    

    或者,您可以简单地 pad 带有适当数量的前导零的数字:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-09
        • 1970-01-01
        • 1970-01-01
        • 2018-12-23
        相关资源
        最近更新 更多