views:

85

answers:

2

I have a string of this format

1.0.x.0

I have to write a regex in javascript that automatically increment the x-- How to do it?

Note, the string given will always be of that format-- no need to test for format validity...

+8  A: 

Try this:

"1.0.123.0".replace(/(\d+\.\d+\.)(\d+)(\.\d+)/, function($0, $1, $2, $3) {
    return $1 + (parseInt($2) + 1) + $3;
});
Gumbo
+2  A: 

Why must it be a regular expression? The notation is consistent and only varies slightly; a regular expression is not necessary.

function incrementStrN(str) {
    var split = str.split('.');
    split[2]++;
    return split.join('.');
}
incrementStrN("1.0.123.0"); // Returns "1.0.124.0"

I know it doesn't look very pretty but it's faster than using a regular expression; plus it's easier to customize; for example you could implement it in such a way so that the section to be incremented can be changed: (see @param sec)

function incrementStrN(str, sec) {
     var split = str.split('.');
     split[sec-1]++;
     return split.join('.');
}

incrementStrN("1.0.123.0", 1); // Returns "2.0.123.0"
incrementStrN("1.0.123.0", 3); // Returns "1.0.124.0"
J-P
regex has less code to write, and is more powerful
Ngu Soon Hui
A flat opinion like that won't get you anywhere. I love regex as much as anyone but there's a time and a place. The fact is, in this situation, a regex will be slower...
J-P