Bram Vanroy
Bram Vanroy

Reputation: 28554

Adding to a string (as numeral) with JS RegEx

Is it possible to add (+1) to a (substring) with regex/replace? For instance, if I have a string (the window location in this case) that ends in #img-{digit}, is it possible with regex to replace the digit with what it was +1?

I can match the hash like this, but I'm not sure how I can extract the number (which can be more than 2 digits! e.g. 12).

var loc = window.location,
    locstr = loc.match(/#img-\d+/),
    // untested:
    locrep = locstr.replace(/\d/, Number($1) + 1);

Let's say that my current hash is #img-4, then I want a JS snippet that changes it to #img-5.

Upvotes: 1

Views: 54

Answers (3)

guest271314
guest271314

Reputation: 1

Note, window.location returns window.location object ; e.g.,

console.log(typeof window.location, typeof window.location.hash);

Try

var loc = window.location.hash
, locrep = loc.match(/[^\d]/g).join("") + (1+Number(loc.match(/\d/g).join("")));

Upvotes: 0

Mukesh Agarwal
Mukesh Agarwal

Reputation: 528

Since you have the string like #img-{digit}, you can use split with - like this

var loc = window.location,
    locstr = loc.split("-");
    var newloc = locstr[0]+parseInt(locstr[1])+1;

Upvotes: 0

anubhava
anubhava

Reputation: 786091

Use a callback in replace:

var locrep = locstr.replace(/\d+/, function($0) { return Number($0) + 1; });
//=> #img-5

Or else:

var locrep = locstr.replace(/(#img-)(\d+)/i, 
                           function($0, $1, $2) { return $1 + (Number($2) + 1); });
//=> #img-5

Upvotes: 2

Related Questions