Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript increment numbers at end of alphanumeric string

I have alphanumeric strings that will always end in a number, but which may have other numbers embedded early on.

I need to increment the numeric ending and return new ID numbers.

Example:

A48-DBD7-398

Which will be incremented in a loop:

A48-DBD7-398
A48-DBD7-399
A48-DBD7-400

How do I separate out the numeric tail from the rest of the string, and then save the two parts into different variables?

I found several other S.O. questions that split numbers out of a string, but they cannot handle mixed alphanumeric characters in the first part -- or else they split out ALL the numbers, regardless where they are. I need to get only the trailing digits.


Update

I found a case where my solution does not work:

ABC123-DE45-1

Duplicates as:

ABC2
ABC3
ABC4

JS Fiddle demo

like image 756
crashwap Avatar asked Mar 18 '15 22:03

crashwap


2 Answers

If you are interested in a different approach you could do something like this:

$('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;
    }
});
like image 97
Pierre Wahlgren Avatar answered Oct 06 '22 01:10

Pierre Wahlgren


My 2 cents: use regex to identify the pattern and increment the last part.

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 );   
  }
}

works with the following formats for example:

  • TEST01A06
  • TEST-100-A100
  • TEST0001B-101
  • TEST001A100
  • TEST001A91
  • TEST1101
  • TEST1010
  • 1010

Demo Repl - https://repl.it/@EdoMagen/Increment-alphanumeric-string

like image 21
Edo Magen Avatar answered Oct 06 '22 00:10

Edo Magen