我的字母数字字符串总是以数字结尾,但可能会在早期嵌入其他数字。
我需要增加数字结尾并返回新的 ID 号。
例子:
A48-DBD7-398
Run Code Online (Sandbox Code Playgroud)
这将在循环中递增:
A48-DBD7-398
A48-DBD7-399
A48-DBD7-400
Run Code Online (Sandbox Code Playgroud)
如何将数字尾部与字符串的其余部分分开,然后将这两部分保存到不同的变量中?
我发现了其他几个将数字从字符串中分离出来的 SO 问题,但它们无法处理第一部分中的混合字母数字字符——否则它们会分离出所有数字,无论它们在哪里。我只需要获取尾随数字。
更新: 这个问题仍然存在
我发现我的解决方案不起作用的情况:
ABC123-DE45-1
Run Code Online (Sandbox Code Playgroud)
重复如下:
ABC2
ABC3
ABC4
Run Code Online (Sandbox Code Playgroud)
如果您对不同的方法感兴趣,您可以执行以下操作:
$('button').click(function () {
var value = $('#in').val(); // get value
for (var i = 1; i <= 5; i++) {
value = value.replace(/(\d+)$/, function (match, n) {
return ++n; // parse to int and increment number
}); // replace using pattern
$('#result')[0].innerHTML += '<br>' + value;
}
});
Run Code Online (Sandbox Code Playgroud)
小智 4
我的 2 美分:使用正则表达式来识别模式并增加最后一部分。
function incrementAlphanumeric(str) {
const numPart = str.match(/(0?[1-9])+$|0?([1-9]+?0+)$/)[0];
const strPart = str.slice(0, str.indexOf(numPart));
const isLastIndexNine = numPart.match(/9$/);
// If we have a leading zero (e.g. - 'L100A099')
// or there is no prefix - we should just increment the number
if (isLastIndexNine || strPart != null) {
return strPart + numPart.replace(/\d+$/, (n) => ++n );
}
// Increment the number and add the missing zero
else {
return strPart + '0' + numPart.replace(/\d+$/, (n) => ++n );
}
}
Run Code Online (Sandbox Code Playgroud)
例如,可以使用以下格式:
演示 Repl - https://repl.it/@EdoMagen/Increment-alphanumeric-string