Jason Kelly
Jason Kelly

Reputation: 2645

Incrementing a number at the end of a string

I'd like some help in writing a JavaScript function that Would detect a hyphen and a number at the end of my string:

ie.

var x = "filenumber-2"

If there is a hyphen at the end of my string then take the number after the hyphen and increment it by 1.

ie.

var x = "filenumber-3"

Upvotes: 3

Views: 119

Answers (3)

Grundy
Grundy

Reputation: 13382

try this

var reg = /-\d+$/
if(reg.test(x)){
    x = x.replace(/(\d+)$/,function(a){return +a+1})
}

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382092

You could do

x = x.replace(/-\d+$/, function(n){ return '-'+(1-n) });

This increments the number only if it's after an hyphen and at end of the string.

Upvotes: 2

Geeky Guy
Geeky Guy

Reputation: 9399

You can go along these lines:

increaseNumberAtEndOfString = function (input) {
    try {
        var ar = input.split("-");
        if (ar.length > 1) {
            var myNumber = Number(ar[ar.length - 1]);
            myNumber++;
            ar[ar.length - 1] = myNumber;
        }
        return ar.join("-");
    } catch (e) {
        throw new Error("Invalid string!");
    }
}

Upvotes: 0

Related Questions