Skip to content Skip to sidebar Skip to footer

How To Increment A Numeric String By +1 With Javascript/jquery

I have the following variable: pageID = 7 I'd like to increment this number on a link: $('#arrowRight').attr('href', 'page.html?='+pageID); So this outputs 7, I'd like to append

Solution 1:

Try this:

parseInt(pageID, 10) + 1

Accordint to your code:

$('#arrowRight').attr('href', 'page.html?='+ (parseInt(pageID, 10) + 1));

Solution 2:

+ happens to be valid operator for both strings and numbers that gives different results when both arguments are numeric and when at least one is not. One of possible workarounds is to use operator that only have numeric context but gives same mathematical result, like -. some_var - -1 will always be same as adding 1 to some_var's numeric value, no matter if it is string or not.

$('#arrowRight').attr('href', 'page.html?='+ (pageID - -1));

Solution 3:

It needs to be a integer, not a string. Try this:

pageID = parseInt(pageID)+1;

Then you can do

$('#arrowRight').attr('href', 'page.html?='+pageID);

Solution 4:

All these solutions assume that your number you want to add 1 to is within the machine precision for an integer. So if you have a large enough number within that string when you add 1 to it won't change the number.

For Example:

parseInt('800000000000000000', 10) + 1 = 800000000000000000

So I wrote a quick solution to the problem

functionaddOne(s) {
    let newNumber = '';
    let continueAdding = true;
    for (let i = s.length - 1; i>= 0; i--) {
        if (continueAdding) {
            let num = parseInt(s[i], 10) + 1;
            if (num < 10) {
                newNumber += num;
                continueAdding = false;
            } else {
                newNumber += '0';
            }
        } else {  
            newNumber +=s[i];
        }
    }
    return newNumber.split("").reverse().join("");
}

Now, using the same example above

addOne('800000000000000000') + 1 = '800000000000000001'

Note that it must stay as a string or you will lose that 1 at the end.

Solution 5:

Simply, $('#arrowRight').attr('href', 'page.html?='+(pageID+1));

The parentheses makes the calculation done first before string concatenation.

Post a Comment for "How To Increment A Numeric String By +1 With Javascript/jquery"