0

I want to change a string-for example- if its "Hello999" it should become "Hello1000" thus increment the number by one but keep the rest. I want to do it using regex but I am not sure how to just "take" the number out of the string and increment it. My code below:

function stringNumber(str){
    var string="";
    if (/^.*\w+$/i.test(str)){ 
        //testing if the end is a number,if not Ill add 1, not increment
        string=str+1;
        return string;
    }
    else if (/^.*\w+\d+$/i.test(str)){
        string=0;
        string+=1;
        //thats wrong because I keep adding a 1, not incrementing
        return string;
    }
}
stringNumber('hello999');

Update version: //Doesnt work as well

function stringNumber(str){
 var string="";
 if (/^.*\w+$/i.test(str)){ 
    string=str+1;
    return string;
 }
 else if (/^.*00\d+$/i.test(str)){
    string=str.replace(/0\d+$/, function(n) { return parseInt(n) + 1; });
//trying to keep 1 zero and replace the second zero PLUS the number following with incremented number
    return string;
 }

}
stringNumber("hello00999");

3 Answers3

2

Use a function as the second argument to the .replace() function:

str.replace(/\d+/, function(match) {
  return Number(match) + 1
})
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
2

Concatenating Strings vs. Incrementing Numbers

If you want to actually increment your number, you'll have to make it an actual numeric value to begin with (as otherwise you would just be concatenating your two strings).

Consider just parsing the numeric part of your string via the Number() function and then incrementing it within a replace() call :

function stringNumber(str){
     // Replace the number at the end of the string 
     return str.replace(/\d+$/, function(n) { return Number(n) + 1; });
}

If you want to extend this to handle scenarios where your string didn't contain a number, you could accomplish this fairly easily as well :

function stringNumber(str){
     // Replace the number at the end of the string or append a 1 if no number
     // was found
     return /\d+$/.test(str) ? str.replace(/\d+$/, function(n) { return Number(n) + 1; }) : str + '1';
}

Example

function stringNumber(str) {
  // Replace the number at the end of the string 
  return str.replace(/\d+$/, function(n) { return Number(n) + 1; });
}
console.log(stringNumber('hello999'));

Update: Now with Padding Strings

Since it sounds like you need to handle padded strings, you could do this through a simple padding function and by checking some edge cases to determine when you need to pad an extra digit :

function stringNumber(str) {
  // Replace the number at the end of the string or add a padded version of your number
  return /\d+$/.test(str) ? str.replace(/\d+$/, function(n) {
      // Determine if we are looking at an edge (i.e. all 9s)
      var rangeToPad = /^9+$/.test(n) ? n.length + 1 : n.length;
      // Pad our result by the specified amount
      return pad(Number(n) + 1, rangeToPad);
    })
    // Or simply add a one to the value (padded by three digits)
    : str + pad(1, 3);
}

function pad(num, size) {
  return ('00000' + num).substr(-size);
}

Padding Example

function stringNumber(str) {
  // Replace the number at the end of the string or add a padded version of your number
  return /\d/.test(str) ? str.replace(/\d+$/, function(n) {
      // Determine if we are looking at an edge (i.e. all 9s)
      var rangeToPad = /^9+$/.test(n) ? n.length + 1 : n.length;
      // Pad our result by the specified amount
      return pad(Number(n) + 1, rangeToPad);
    })
    // Or simply add a one to the value (padded by three digits)
    : str + pad(1, 3);
}

function pad(num, size) {
  return ('00000' + num).substr(-size);
}

console.log('hello => ' + stringNumber('hello'));
console.log('hello001 => ' + stringNumber('hello001'));
console.log('hello998 => ' + stringNumber('hello998'));
console.log('hello999 => ' + stringNumber('hello999'));
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • Thank you. Could you explain the part { return Number(n) + 1; - what is exactly happening?(Im a beginner). Also, how could I turn hello000 into hello001 and not into hello1? –  May 24 '16 at 17:19
  • Sure. The `return Number(n)` call is actually going to take the numeric value from your string and convert it into an integer, which will allow you to do things like add, subtract, etc. to it. Handling zero padded numbers can likely make things a bit trickier however. – Rion Williams May 24 '16 at 17:22
  • Oh okay. Would it be the same if I did: function (n) {parseInt(n)+1;}); ? –  May 24 '16 at 17:30
  • Essentially yes, although there are some differences between the two that are covered in [this answer](http://stackoverflow.com/a/4090577/557445) with regards to leading zeroes, etc. Additionally, I've added an example for handling values with leading zeroes for you as well. – Rion Williams May 24 '16 at 17:38
  • Your code works, i just understand pretty much nothing as you included a bunch of complex stuff and I am a beginner! –  May 24 '16 at 17:44
  • I can go back and try to annotate it a bit more to specify exactly what is going on. – Rion Williams May 24 '16 at 17:54
  • I included another version (I don't know how to post code in the comments section)- why isn't that working? I kept 1 zero and replaced the other zero with the incremented number.. –  May 24 '16 at 18:04
  • This is a result of the padding function, try changing `00000` to `00000000`. I just used 5 digits as an example, but more would allow larger padded strings. I'm creating a longer more well explained example of these functions for you as well. – Rion Williams May 24 '16 at 18:06
  • My code would be wrong too if it wasn't hello00999 but hello000999. However, i really just want to understand why my code isn't working for hello00999-I m trying to learn and if I don't know what was wrong in my code Im gonna repeat those mistakes, so could you explain what is wrong in my code –  May 24 '16 at 18:14
  • [Here](https://gist.github.com/Rionmonster/1babe751781a478146f63431af31f32c) is a more detailed breakdown of these functions. The issue that you mentioned regarding `hello00999` is fixed when the change is made to the `pad()` function. – Rion Williams May 24 '16 at 18:16
  • The reason that your existing code isn't working is because a zero-padded number like `00999` isn't an actual number but is instead a string. You would need to parse it as an number and then properly pad it as what was done in the examples I provided (this is why you examine how many digits you have using the `rangeToPad` variable, so that you can keep track of the length. Also it's worth noting that in your first if statement you use the `\w` character in your expression, which actually matches any numbers or letters, so your second else statement isn't actually being executed. – Rion Williams May 24 '16 at 18:21
  • Okay thanks. I exchanged the w+ with D and the if statement is now being executed. I wonder, couldn't I use Number or parseInt JUST on the number 1. which isn't a zero(check is it zero-yes,no) and 2 ALSO on ONE zero right before the number? Like is there a way using reggae to check for number unequal to 0 PLUS the zero right before it, replace ONLY that part (number 1-9 and 0 right before it) –  May 24 '16 at 18:35
1

Just for fun...

function stringNumber(str){
    if (str.match(/\d+/)){
      var t = str.match(/\d+/)[0];
      var n = parseInt(t) + 1;
      return str.replace(/([0]*)(\d+)/, "$1" + n);
    }
    return str+"1";
}
console.log(stringNumber("hello00123")); // hello00124
console.log(stringNumber("hello1236")); // hello1237
console.log(stringNumber("hello00")); // hello01
console.log(stringNumber("hello")); // hello1

Too long for a simple task though. Anyaway, hope it helps :)

UPDATE:I just realized that you just add 1 if the string does not contain any number. So I just modified it a bit.

JanLeeYu
  • 981
  • 2
  • 9
  • 24
  • what does the [0] stand for? –  May 25 '16 at 04:19
  • Well it just retrieves the first group captured because the `match()` function returns an array of captured groups.. In the case of `"hello00123"`, the first group is `00123`.That's it. – JanLeeYu May 25 '16 at 05:22
  • And if you mean this `[0]` in the group `"([0]*)(\d+)"`, it just denotes a character class that matches the character `"0"`. – JanLeeYu May 25 '16 at 06:02
  • ah okay so the [0] in ([0]*)(\d+) actually means the number 0 and not the first (zero) captured ground, right? –  May 25 '16 at 23:10
  • You are right. But since has an `*` after it, it will capture all the leading `0` (if there are any. `*` means 0 or more)but the last `0` is not included because it is captured by the `(\d+)` up to the last digit. – JanLeeYu May 26 '16 at 01:39
  • also, if you enter `"hell23o00123003"`, the output will be `"hell24o00123004"`.Just let me know if its ok with you. – JanLeeYu May 26 '16 at 01:40