crashwap
crashwap

Reputation: 3062

Increment numbers at end of alphanumeric string in JavaScript

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

Upvotes: 6

Views: 4682

Answers (5)

crashwap
crashwap

Reputation: 3062

I figured it out, and am posting the question for future seekers.

JS Fiddle demo

HTML:

<input id="in" type="text" value="A48-DBD7-395" />
<button>Go</button>
<div id="result"></div>

js/jQ:

$('button').click(function(){
    var ser = $('#in').val();
    var num = parseInt(ser.match(/\d+$/));
    var pos = ser.indexOf(num);
    var str = ser.slice(0,pos);

    for (n=1;n<=5;n++){
        num++;
        ser = str + num;
        $('#result').html( $('#result').html() +'<br>'+ser);
    }
});

Upvotes: 0

Scott Clark
Scott Clark

Reputation: 628

const s = "A48-DBD7-398";
s.split('-').reduce((a,b)=>{
      if(Number(b)){b = Number(b) + 1}
      return a +'-'+ b; 
    })

> "A48-DBD7-399"

Upvotes: -1

user9350
user9350

Reputation: 41

Here is another solution, in case it helps

$('button').click(function() {
  var ser = $('#in').val();
  var arr = ser.split("-");

  var num = parseInt(arr[arr.length - 1]);
  arr.splice(-1, 1);
  var str = arr.join ('-');  

  for (n = 1; n <= 5; n++) {
    num++;       
    ser = str + '-' + num;    
    $('#result').html($('#result').html() + '<br>' + ser);
  }
});
div{width:80%;margin-top:30px;background:wheat;}
<input id="in" type="text" value="ABC123-DE45-1" />
<button>Go</button>
<div id="result"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 2

Edo Magen
Edo Magen

Reputation: 166

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

Upvotes: 4

Pierre Wahlgren
Pierre Wahlgren

Reputation: 875

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

Upvotes: 6

Related Questions