I have the following JS immbedded in a page:
var round = Math.round; var id = $(this).attr("id"); var len = id.length; var indexPos = len -1; // index of the number so that we can split this up and used it as a title var pasType = id.substring(0, indexPos); // adult, child or infant var ind = round(id.substring(indexPos)); // converts the string index to an integer var number = (id.substring(indexPos) + 1); // creates the number that will go in the title window.alert(number);
id
will be something like adult0, and I need to take that string and split it into adult and 0 - this part works fine.
The problem comes in when I try to increment the 0. As you can see I use Math.round to convert it to an integer, and then add 1 to it - I expect 0 to be 1 after this. However, it doesn't seem to be converting it to integer, because I get 01
, not 1
. When testing this with adult1 the alert I get is 11
.
I'm using this question for reference, and have also tried var number += id.substring(indexPos);
, which breaks the JS (unexpected identifier '+='
)
Does anyone know what I'm doing wrong? Is there a better way of doing this?
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .
The parseInt()
function parses a string
and returns an integer
,10 is the Radix or Base [DOC]
var number = parseInt(id.substring(indexPos) , 10 ) + 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With