Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment last number in string

given the following string:

Backticks[0].Folders[0]

I need to increment the latter number.

I'm not an expert with Regexp replacements, I tried this but it also selects the bracket.

href = href.replace(/\d+]$/gi, matchedNumber++);

Is it possible to do the selection, incremental and replacement in a one liner?

like image 957
Shimmy Weitzhandler Avatar asked May 09 '13 00:05

Shimmy Weitzhandler


2 Answers

It is possible to do in one line

'Ace[0].Folders[0]'.replace(/\d+(?=]$)/, function(i) { return parseInt(i) + 1; })
like image 99
zerkms Avatar answered Sep 29 '22 07:09

zerkms


Use a positive lookahead:

/\d(?=]$)/gi

This will make sure there is any character after then the end of string after the digit, without including it in the replace.

If you would like to increment it, you could use match and parseInt:

var href = this.href;
var re = /\d(?=.$)/gi
href = href.replace(re, parseInt(href.match(re))+1);

Here is a page where you can learn more about this.

Here is a fiddle.

like image 39
tckmn Avatar answered Sep 29 '22 07:09

tckmn