首页 > 解决方案 > 在javascript中添加带有前导零的数字字符串

问题描述

以下是我的代码,除了前导零之外,它在大多数情况下都可以正常工作。它应该保留尾随零,例如 -001 + 1 = 002

代码 -

function incrementString (str) {
  if(str === '') return "1";
  
  if(!str.slice(-1).match(/\d/)) return `${str}1`;
  
  const replacer = x => {
    // Check if number 
    return (parseInt(x) + 1).toString();
  }
  
  return str.replace(/\d+/g, replacer )
}

// Return foobar2 which is correct
console.log(incrementString("foobar1"))

// Return foobar100 which is correct
console.log(incrementString("foobar099"))

// Return foobar2 which is incorrect, is should be foobar002
console.log(incrementString("foobar001"))

// Return foobar1 which is incorrect, is should be foobar001
console.log(incrementString("foobar000"))

// Return foobar101 which is incorrect, is should be foobar0101
console.log(incrementString("foobar0100"))

标签: javascripthtmlregexreactjsecmascript-6

解决方案


您可以使用此正则表达式解决方案:

function incrementString (str) {
  if(str === '') return "1";
  
  if(!str.slice(-1).match(/\d/)) return `${str}1`;
  
  const replacer = (m, g1, g2) => {
    // Check if number 
    var nn = (g1?g1:"") + (parseInt(g2) + 1).toString()
    return nn.slice(-1 * m.length)

  }
  
  return str.replace(/(0*)(\d+)/g, replacer )
}

// Return foobar2
console.log(incrementString("foobar1"))

// Return foobar100
console.log(incrementString("foobar099"))

// Return foobar002
console.log(incrementString("foobar001"))

// Return foobar001
console.log(incrementString("foobar000"))

// Return foobar0101
console.log(incrementString("foobar0100"))

// Return foobar01000
console.log(incrementString("foobar00999"))

// Return foobar010
console.log(incrementString("foobar009"))


推荐阅读