Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a string in Javascript

Tags:

javascript

Let's say I have the following string:

aRandomString

I'm then checking my database to see if that string has been used before (or if there's any string that starts with the given one). If it has, I'd like to increment it. The result would be the following:

aRandomString1

If that string exists, it would become aRandomString2, and so on. I'm assuming I need to complete the following steps: 1. Check for trailing numbers or set to 0, 2. Increment those trailing numbers by 1, append that number to the original string. Just trying to figure out a solid way to accomplish this!

Update

This is what I have so far:

var incrementString = function( str ){
    var regexp = /\d+$/g;
    if( str.match(regexp) )
    {
        var trailingNumbers = str.match( regexp )[0];
        var number = parseInt(trailingNumbers);
        number += 1;

        // Replace the trailing numbers and put back incremented
        str = str.replace(/\d+$/g , '');
        str += number;
    }else{
        str += "1";
    }
    return str;
}

I feel like this should be easier though.

like image 675
Nick ONeill Avatar asked Feb 21 '26 20:02

Nick ONeill


1 Answers

function incrementString(str) {
  // Find the trailing number or it will match the empty string
  var count = str.match(/\d*$/);

  // Take the substring up until where the integer was matched
  // Concatenate it to the matched count incremented by 1
  return str.substr(0, count.index) + (++count[0]);
};

If the match is the empty string, incrementing it will first cast the empty string to an integer, resulting the value of 0. Next it preforms the increment, resulting the value of 1.

like image 179
adamduren Avatar answered Feb 24 '26 09:02

adamduren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!