Get and replace the last number on a string with J

2019-03-26 01:24发布

问题:

If I have the string:

var myStr = "foo_0_bar_0";

and I guess we should have a function called getAndIncrementLastNumber(str)

so if I do this:

myStr = getAndIncrementLastNumber(str); // "foo_0_bar_1"

Taking on considerations that there could be another text instead of foo and bar and there might not be underscores or there might be more than one underscore;

Is there any way with JavaScript or jQuery with .replace() and some RegEx?

回答1:

You can use the regular expression /[0-9]+(?!.*[0-9])/ to find the last number in a string (source: http://frightanic.wordpress.com/2007/06/08/regex-match-last-occurrence/). This function, using that regex with match(), parseInt() and replace(), should do what you need:

function increment_last(v) {
    return v.replace(/[0-9]+(?!.*[0-9])/, parseInt(v.match(/[0-9]+(?!.*[0-9])/), 10)+1);
}

Probably not terribly efficient, but for short strings, it shouldn't matter.

EDIT: Here's a slightly better way, using a callback function instead of searching the string twice:

function increment_last(v) {
    return v.replace(/[0-9]+(?!.*[0-9])/, function(match) {
        return parseInt(match, 10)+1;
    });
}


回答2:

Here's how I do it:

function getAndIncrementLastNumber(str) {
    return str.replace(/\d+$/, function(s) {
        return ++s;
    });
}

Fiddle

Or also this, special thanks to Eric:

function getAndIncrementLastNumber(str) {
    return str.replace(/\d+$/, function(s) {
        return +s+1;
    });
}

Fiddle



回答3:

try this demo please http://jsfiddle.net/STrR6/1/ or http://jsfiddle.net/Mnsy3/

code

existingId = 'foo_0_bar_0';
newIdOnly = existingId.replace(/foo_0_bar_(\d+)/g, "$1");
alert(newIdOnly);

getAndIncrementLastNumber(existingId);

function getAndIncrementLastNumber(existingId){
    alert(existingId);
newId = existingId.replace(/(\d+)/g, function(match, number) {
    return parseInt(number) + 1;
});
alert(newId);
}
​

or

   existingId = 'foo_0_bar_0';
newIdOnly = existingId.replace(/foo_0_bar_(\d+)/g, "$1");
alert(newIdOnly);

getAndIncrementLastNumber(existingId);

function getAndIncrementLastNumber(existingId){
    alert(existingId);
    newId = existingId.replace(/\d+$/g, function(number) {
    return parseInt(number) + 1;
});
alert("New ID ==> " + newId);
}
​


回答4:

Will the numbers be seperated with some characters? What I understood from you question is your string may look like this 78_asd_0_798_fgssdflh__0_2323 !! If this is the case, first you need to strip out all the characters and underscores in just one go. And then whatever you have stripped out you can either replace with comma or some thing.

So you will basically have str1: 78_asd_0_798_fgssdflh__0_2323 ; str2: 78,0,0,798,2323.

str2 need not be a string either you can just save them into a variable array and get the max number and increment it.

My next question is does that suffice your problem? If you have to replace the largest number with this incremented number then you have to replace the occurence of this number in str1 and replace it with your result.

Hope this helps. For replace using jquery, you can probably look into JQuery removing '-' character from string it is just an example but you will have an idea.



回答5:

in regex try this:

function getAndIncrementLastNumber(str){
   var myRe = /\d+[0-9]{0}$/g;  
   var myArray = myRe.exec(str);
   return parseInt(myArray[0])+1;​
}

demo : http://jsfiddle.net/F9ssP/1/



回答6:

If you want to only get the last number of string, Here is a good way using parseInt()

if(Stringname.substr(-3)==parseInt(Stringname.substr(-3)))
var b=Stringname.substr(-3);
else if(Stringname.substr(-2)==parseInt(Stringname.substr(-2)))
var b=Stringname.substr(-2);
else
var b=Stringname.substr(-1);

It checks and give the correct answer and store it in variable b for 1 digit number and upto 3 digit number. You can make it to any if you got the logic



回答7:

@Brilliant is right, +1, I just wanted to provide a version of his answer with 2 modifications:

  • Remove the unnecessary negative look-ahead operator.
  • Add the ability to add a number in the end, in case it doesn't exist.

```

/**
 * Increments the last integer number in the string. Optionally adds a number to it
 * @param {string} str The string
 * @param {boolean} addIfNoNumber Whether or not it should add a number in case the provided string has no number at the end
 */
function incrementLast(str, addIfNoNumber) {
    if (str === null || str === undefined) throw Error('Argument \'str\' should be null or undefined');
    const regex = /[0-9]+$/;
    if (str.match(regex)) {
        return str.replace(regex, (match) => {
            return parseInt(match, 10) + 1;
        });
    }
    return addIfNoNumber ? str + 1 : str;
}

Tests:

describe('incrementLast', () => {
        it('When 0', () => {
            assert.equal(incrementLast('something0'), 'something1');
        });
        it('When number with one digit', () => {
            assert.equal(incrementLast('something9'), 'something10');
        });
        it('When big number', () => {
            assert.equal(incrementLast('something9999'), 'something10000');
        });
        it('When number in the number', () => {
            assert.equal(incrementLast('1some2thing9999'), '1some2thing10000');
        });
        it('When no number', () => {
            assert.equal(incrementLast('1some2thing'), '1some2thing');
        });
        it('When no number padding addIfNoNumber', () => {
            assert.equal(incrementLast('1some2thing', true), '1some2thing1');
        });
    });