I am writing a code to check if a certain number of credit card number inputs is valid or not. I have written:
function validCreditCard(value) {
// accept only digits, dashes or spaces
if (value.trim().length <= 1) return 'Value entered must be greater than 1';
if (/[^0-9\s]+/.test(value)) return false;
// Remove all white spaces
value = value.replace(/\D/g, '');
for (var i = 0; i < value.length; i++) {
// code goes here
// Loop through the string from the rightmost moving left and double the value of every second digit.
}
I have been trying to wrap my head around how to Loop through the string from the rightmost moving left and double the value of every second digit since the length of the string can be even or odd. For example, for an input with length 16(even), the first number to the left will be the 15th position (index 14) and for an input with odd length like 11, the first number to the left will be the 10th position(index 9). I have written a program that didn't work for both cases and now I want to write one to cater for both. How best can I achieve this without creating two separate checks to see if the length of the input is odd or even?
P.S: Some implementations online don't work for both cases too.