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

前端 未结 7 1538
挽巷
挽巷 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: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');
            });
        });
    

提交回复
热议问题