javascript - why is string.split returning extra empty entries in this example?


Keywords:javascript 


Question: 


2 Answers: 

This should work.

function formatDate(userDate) {
  // format from M/D/YYYY to YYYYMMDD
  console.log(userDate);
  var dateParts = userDate.split("/");
  return dateParts[2] + dateParts[0] + dateParts[1];
 }
console.log(formatDate("12/31/2014"));
 

Two issues here

  • Replace the regex for split with /\//
  • Reduce the index of each of the items

i.e.

var day = dateParts[1],
month = dateParts[0],
year = dateParts[2];

Demo

function formatDate(userDate) {
  var dateParts = userDate.split(/\//);
  var day = pad0(dateParts[1]), month = pad0(dateParts[0]), year = dateParts[2];
  return year + month + day;
}

function pad0(input)
{
   return ("0" + input).slice(-2);
}

console.log(formatDate("12/31/2014"));