增加字符串末尾的数字

时间:2022-09-19 17:58:05

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

我想帮助编写一个JavaScript函数来检测字符串末尾的连字符和数字:

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.

如果在我的字符串末尾有一个连字符,则取连字符后的数字并将其递增1。

ie.

即。

var x = "filenumber-3"

3 个解决方案

#1


2  

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.

仅当它在连字符之后和字符串结尾处时才会增加数字。

#2


0  

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!");
    }
}

#3


0  

try this

尝试这个

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

#1


2  

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.

仅当它在连字符之后和字符串结尾处时才会增加数字。

#2


0  

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!");
    }
}

#3


0  

try this

尝试这个

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