Dziamid
Dziamid

Reputation: 11571

How to increase each number in a string?

I need to search a string for any numbers in it and increase the numbers by 1. So that this 'sermon[thesis][1][name][2]' becomes 'sermon[thesis][2][name][3]'.

Upvotes: 2

Views: 356

Answers (4)

Rion Williams
Rion Williams

Reputation: 76547

You can use the replace() function to match any number with a regular expression and then return that value incremented by 1 to replace it:

var string = '[1][2]';
string.replace(/[0-9]+/g,function(e){return parseInt(e,10)+1})); //Returns [2][3]

Working Example

Upvotes: 1

MacMac
MacMac

Reputation: 35301

This will do the trick:

"sermon[thesis][1][name][2]".replace(/\[(\d+)\]/g, function(match, number) {
    return "[" + (Number(number) + 1) + "]";
});

Working demo: jsFiddle.

EDIT:

To increment the last number, you would add a dollar sign $ before the last /, here's a demo: jsFiddle.

Upvotes: 5

Jeffrey Zhao
Jeffrey Zhao

Reputation: 5023

You can do something like this:

var str = "sermon[thesis][1][name][2]";
var newStr = str.replace(new RegExp("\\d+", "g"), function (n) {
    return parseInt(a, 10) + 1;
});

Basicly, the function would be called with the text been captured by the expression \d+,the text return from the function would be use to replace the captured text.

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227190

You can use replace, it can actually take a function as the replacement "string".

var str = 'sermon[thesis][1][name][2]';
str = str.replace(/(\d+)/g, function(a){
   return parseInt(a,10) + 1;
});
console.log(str); //'sermon[thesis][2][name][3]'

Upvotes: 2

Related Questions