Tuesday, April 5, 2011

JavaScript: add or subtract from number in string

I have a string that looks like "(3) New stuff" where 3 can be any number.
I would like to add or subtract to this number.

I figured out the following way:

var thenumber = string.match((/\d+/));
thenumber++;
string = string.replace(/\(\d+\)/ ,'('+ thenumber +')');

Is there a more elegant way to do it?

From stackoverflow
  • Short of extending the String object, it looks good to me.

    String.prototype.incrementNumber = function () {
      var thenumber = string.match((/\d+/));
      thenumber++;
      return this.replace(/\(\d+\)/ ,'('+ thenumber +')');
    }
    

    Usage would then be:

    alert("(2) New Stuff".incrementNumber());
    
    Allain Lalonde : Unlike Array, I don't think extending string is that bad. Since how many times do you iterate over String objects?
    Christian Nunciato : I like this approach as well, myself.
  • I believe your method is the best elegant you can have for following reasons:

    • since the input is not a "clean" number, you do need to involve some sort of string parser. Using regular expressions is the very code-efficient method to do it
    • by looking at the code, it's clear what it does

    short of wrapping this into a function, I don't think there's much more to be done

  • Another way:

    string = string.replace(/\((\d+)\)/ , function($0, $1) { return "(" + (parseInt($1, 10) + 1) + ")"; });
    
  • As galets says, I don't think your solution is a bad one but here is a function that will add a specified value to a number in a specified position in a string.

    var str = "fluff (3) stringy 9 and 14 other things";
    
    function stringIncrement( str, inc, start ) {
        start = start || 0;
        var count = 0;
        return str.replace( /(\d+)/g, function() {
            if( count++ == start ) {
                return(
                    arguments[0]
                    .substr( RegExp.lastIndex )
                    .replace( /\d+/, parseInt(arguments[1])+inc )
                );
            } else {
                return arguments[0];
            }
        })
    }
    
    // fluff (6) stringy 9 and 14 other things :: 3 is added to the first number
    alert( stringIncrement(str, 3, 0) );
    
    // fluff (3) stringy 6 and 14 other things :: -3 is added to the second number
    alert( stringIncrement(str, -3, 1) );
    
    // fluff (3) stringy 9 and 24 other things :: 10 is added to the third number
    alert( stringIncrement(str, 10, 2) );
    
  • I believe Gumbo was on the right track

    "(42) plus (1)".replace(/\((\d+)\)/g, function(a,n){ return "("+ (+n+1) +")"; });
    

0 comments:

Post a Comment