1

I have a html table. One column contains date values. I want to extract month of those dates and print it in the console. Date format is yyyy-MM-dd. Here is my code:

var myTable = document.getElementById('openDispatchNoteTable');

for (var i = 0 ; i < myTable.rows.length ; i++) {
    console.log("date : " + myTable.rows[i].cells[6].innerText);
}

myTable.rows[i].cells[6].innerText gives 2018-November-14 as the output.

Can you please help me to solve this problem?

3 Answers3

2

if format is the same in all of outputs - then use regexp .innerText.match(/[a-z]+/i)[0]

console.log(document.querySelector('div').innerText.match(/[a-z]+/i)[0])
<div>2018-November-14</div>

Also i found good internationalized solution here: get month name from date Second best answer uses toLocaleString.

Smollet777
  • 1,618
  • 1
  • 16
  • 15
1

In your case you can use the replace() method of Javascript.

Use this replace(/[^a-zA-Z ]/g, "") regex which will replace everything with "" other then characters.

var myTable = document.getElementById("myTable");
for (var i = 1; i < myTable.rows.length; i++) {
  console.log("Actual Date : " + myTable.rows[i].cells[0].innerText);
  console.log("Only Month : " + myTable.rows[i].cells[0].innerText.replace(/[^a-zA-Z ]/g, ""));
}
<table id="myTable" border='1'>
  <tr>
    <th>Date</th>
  </tr>
  <tr>
    <td>
      28-November-2018
    </td>
  </tr>
  <tr>
    <td>
      29-November-2018
    </td>
  </tr>
  <tr>
    <td>
      30-November-2018
    </td>
  </tr>
</table>
Smollet777
  • 1,618
  • 1
  • 16
  • 15
Mohan Rajput
  • 634
  • 9
  • 21
0

I highly recommend using momentJS. It has a very elaborate API to handle things just like your need. In this case, the moment object can get the date in your format and then you can use the month function to extract the month.

Gilad Bar
  • 1,302
  • 8
  • 17