开发者

Chunk a string every odd and even position

I know nothing about javascript.

Assuming the string "3005600008000", I need to find a way to multiply all the digits in the odd numbered positions by 2 and the digits in the even numbered positions by 1.

This pseudo code I wrote outputs (I think) TRUE for the odd numbers (i.e. "0"),

var camid;
var LN= camid.length;
var mychar = camid.charAt(LN%2);

var arr = new Array(camid);
for(var i=0; i<arr.length; i++) {
    var value = arr[i]%2;
    Alert(i =" "+value);
}

I am not sure this is right: I don't believe it's chunking/splitting the string at odd (And later even) positions.

How do I that? Can you please provide some hints?

/=================================================/

My goal is to implement in a web page a validation routine for a smartcard id number.

The logic I am trying to implement is as follows:

· 1) Starting from the left, multiply all the digits in the odd numbered positions by 2 and the digits in the even numbered positions by 1.

· 2) If the result of a multiplication of a single digit by 2 results in a two-digit number (say "7 x 2 = 14"), add the digits of th开发者_StackOverflowe result together to produce a new single-digit result ("1+4=5").

· 3) Add all single-digit results together.

· 4) The check digit is the amount you must add to this result in order to reach the next highest multiple of ten. For instance, if the sum in step #3 is 22, to reach the next highest multiple of 10 (which is 30) you must add 8 to 22. Thus the check digit is 8.

That is the whole idea. Google searches on smartcard id validation returned nothing and I am beginning to think this is overkill to do this in Javascript...

Any input welcome.


var theArray = camid.split(''); // create an array entry for each digit in camid
var size = theArray.length, i, eachValue;
for(i = 0; i < size; i++) { // iterate over each digit
  eachValue = parseInt(theArray[i], 10); // test each string digit for an integer
  if(!isNaN(eachValue)) {
    alert((eachValue % 2) ? eachValue * 2 : eachValue); // if mod outputs 1 / true (due to odd number) multiply the value by 2. If mod outputs 0 / false output value
  }
}


I discovered that what I am trying to do is called a Luhn validation.

I found an algorithm right here.

http://sites.google.com/site/abapexamples/javascript/luhn-validation

Thanks for taking the time to help me out. Much appreciated.


It looks like you might be building to a Luhn validation. If so, notice that you need to count odd/even from the RIGHT not the left of the string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜