0

Currently using the below code which works well to parse my swiped data. However I need to show the month and year (as example) as January 2019 in separate fields. Right now it does it as 01 19. Anyway to edit this code?

function setFromCCS(ccs) {

    var index1 = ccs.indexOf("%B") + 2;
    var index2 = ccs.indexOf("^") + 1;
    var index3 = ccs.indexOf("^", index2 + 1) + 1;

    var cardNumber = ccs.substring( index1, index2 - 1);
    var expMonth = ccs.substr(index3, 2);
    var expYear = ccs.substr(index3 + 2, 2);
    var holderName = ccs.substring(index2, index3 - 1);

    $("#cn").val(cardNumber);
    $("#em").val(expMonth);
    $("#ey").val(expYear);
    $("#hn").val(holderName);
}
Card number: <input type="text" name="ccnum" id="cn"><br />
Card exp month: <input type="text" name="ccnum" id="em"><br />
Card exp year: <input type="text" name="ccnum" id="ey"><br />
Card holder name: <input type="text" name="ccnum" id="hn"><br />
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
MHeredia
  • 51
  • 1
  • 11

2 Answers2

1

How about this: https://jsfiddle.net/m4fo5250/1/

function setFromCCS(ccs) {

    var index1 = ccs.indexOf("%B") + 2;
    var index2 = ccs.indexOf("^") + 1;
    var index3 = ccs.indexOf("^", index2 + 1) + 1;

    var cardNumber = ccs.substring( index1, index2 - 1);
    var expMonth = ccs.substr(index3, 2);
    var expYear = ccs.substr(index3 + 2, 2);
    var holderName = ccs.substring(index2, index3 - 1);

    var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

    $("#cn").val(cardNumber);
    $("#em").val(monthNames[+expMonth-1);
    $("#ey").val("20"+expYear);
    $("#hn").val(holderName);
}

We can store all the month names in an array. Then we can get the month name from the array by using the month number as an index - though, keep in mind, arrays start with an index of 0 so we'll need to compensate by doing expMonth-1.

And a heads up - this solution won't work past the year 2099 because I'm simply prefacing the year with 20. ;)

Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
0

You can create an array with the month names called monthNames, and then call it: monthNames[0] for january.

Example below is just a reference:

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

document.write("Arrays start from 0 so 0 = " + monthNames[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

hope it helped

Serge Inácio
  • 1,366
  • 9
  • 22