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...
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...
Try this:
"1.0.123.0".replace(/(\d+\.\d+\.)(\d+)(\.\d+)/, function($0, $1, $2, $3) {
return $1 + (parseInt($2) + 1) + $3;
});
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"