Get and replace the last number on a string with JavaScript or jQuery

前端 未结 7 1550
挽巷
挽巷 2021-02-14 11:02

If I have the string:

var myStr = \"foo_0_bar_0\";

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

相关标签:
7条回答
  • 2021-02-14 11:11

    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);
    }
    ​
    
    0 讨论(0)
  • 2021-02-14 11:15

    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/

    0 讨论(0)
  • 2021-02-14 11:18

    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;
        });
    }
    
    0 讨论(0)
  • 2021-02-14 11:21

    @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');
            });
        });
    
    0 讨论(0)
  • 2021-02-14 11:25

    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.

    0 讨论(0)
  • 2021-02-14 11:26

    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

    0 讨论(0)
提交回复
热议问题