Neil
Neil

Reputation: 8111

Incrementing a number in a string

I have the following string: 0-3-terms and I need to increment the 3 by 20 every time I click a button, also the start value might not always be 3 but I'll use it in this example..

I managed to do this using substring but it was so messy, I'd rather see if it's possible using Regex but I'm not good with Regex. So far I got here, I thought I would use the two hyphens to find the number I need to increment.

var str = '0-3-terms';
var patt = /0-[0-9]+-/;
var match = str.match(patt)[0];

//output ["0-3-"]

How can I increment the number 3 by 20 and insert it back in to the str, so I get:

0-23-terms, 0-43-terms, 0-63-terms etc.

Upvotes: 0

Views: 76

Answers (3)

Sampath Liyanage
Sampath Liyanage

Reputation: 4896

I don't understand why you are using regex. Simply store the value and create string when the button is called..

//first value
var value = 3;
var str = '0-3-terms';

//after clicking the button
value = value+20;
str = "0-" + value + "-terms"

Upvotes: 0

Colin DeClue
Colin DeClue

Reputation: 2244

Another option is to use .split instead of regex, if you prefer. That would look like this:

var str = '0-3-terms';
var split = str.split('-');
split[1] = +split[1] + 20;
var result = split.join('-');
alert(result);

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

You're doing a replacement. So use .replace.

var str = '0-3-terms';
var patt = /-(\d+)-/;
var result = str.replace(patt,function(_,n) {return "-"+(+n+20)+"-";});

Upvotes: 5

Related Questions