One would think that converting a 3 character abbreviation to a number representation would be an easy task. JavaScript says "NOPE!".
$(selector).each(function() {
// convert month abbreviation to numerical representation
var monthStr = $(this).text().match(/[^\/]*/)[0];
var months = {
JAN: 1,
FEB: 2,
MAR: 3,
APR: 4,
MAY: 5,
JUN: 6,
JUL: 7,
AUG: 8,
SEP: 9,
OCT: 10,
NOV: 11,
DEC: 12
};
var month = months[monthStr].toString();
var date = $(this).text().replace(monthStr, month);
$(this).text(date);
});
Even though the code is valid and works, my console still goes haywire with the following error:
Uncaught TypeError: Cannot call method 'toString' of undefined
which makes absolutely no sense since the selector's text is replaced correctly (at least according to the eye).
The issue seems to begin when I declare the 'monthStr' variable. If I set it to a static 'MAR' as an example and remove the '.toString()' from my 'month' variable definition the error no longer occurs.
Furthermore, the only thing saving the code is the already mentioned '.toString()' conversion for my month variable. If it was not there I would end up with a 'undefined' value.
Just wanted to share my JavaScript-being-dumb experience of the day and hope that someone could possibly elaborate on why this error is being thrown, even when the code works flawlessly.