面临递增值问题,我必须递增数字字符串值。
var text = "SYN00099";
var getPart = text.replace(/[^\d.]/g, ''); // returns 00099
var num = parseInt(getPart); // returns 99
var newVal = num + 1; // returns 100
var reg = new RegExp(num.toString()); // create dynamic regexp
var newstring = text.replace(reg, newVal.toString()); // returns SYN000100
console.log(num);
console.log(newVal);
console.log(reg);
console.log(newstring);
这是我在我的代码中尝试过的。这可以正常工作,但此代码的问题是,如果数字增加,它会增加字符串长度。例如,如果它的最后一位数字是 9,那么它将变为 10,但它不会从字符串中删除 1 个零。
最佳答案
自增后,可以用String.padStart 在num + 1
字符串前填'0'功能如下。
var newVal = (num + 1).toString().padStart(getPart.length, '0'); // returns 00100
使用该函数,它将在 100
字符串前面填充两次 0
(因此总长度 = 5 = getPart string length
)
下面是工作示例。
var text = "SYN00099";
var getPart = text.replace(/[^\d.]/g, ''); // returns 00099
var num = parseInt(getPart); // returns 99
var newVal = (num + 1).toString().padStart(getPart.length, '0'); // returns 00100
var newstring = text.replace(getPart, newVal); // returns SYN000100
console.log(num);
console.log(newVal);
console.log(newstring);
关于javascript - 增加字符串内的数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64443683/