javascript - 在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"))
解决方案
您可以使用此正则表达式解决方案:
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"))
推荐阅读
- dataframe - 'numpy.int64' 对象在通过字典迭代时不可迭代
- azure - Azure Active Directory B2C - 在数据库中维护用户
- ruby - 反向外壳 - 如何让服务器打印发送给客户端的多条消息
- perl - 有没有办法在 if 语句中将变量设置为彼此相等?
- android - Firestore 数据未显示在 RecyclerView 中
- dart - 动画小部件推送其他小部件
- python - 拟合曲线时如何修复“TypeError:f() 需要 3 个位置参数时给出 4 个错误”
- html - 当元素包含长文本时,如何强制伪“后”元素的宽度?
- javascript - 如何遍历对象数组并过滤掉同一小时内的项目
- ios - 在某些操作系统版本中未调用 WKHTTPCookieStore getAllCookies 完成处理程序