lets say I have two string that looks like this:
Is there a Regex pattern I can use to extract the day number?
I am currently using Javascript, and would like to make a function to do the heavy lifting.. I have started on one below, but cant seem to get it working.
function extractDate(str) {
return str;
}
Please share with me a way to make it work
Here is a Regex function that will get rid of the day of the week and time in the elements:
/(january|february|march|april|june|july|august|september|october|november|december) \d{1,2}, \d{4}/gi
Here's a working example of that regex, then logging it.
const x = document.getElementById("target").children;
const dateRegex = (/(january|february|march|april|june|july|august|september|october|november|december) \d{1,2}, \d{4}/gi);
function extractDate(str) {
const parsedDate = str.match(dateRegex);
return parsedDate;
}
for (let i = 0; i < x.length; i++) {
// Return as string
var strDate = extractDate(x[i].innerText).toString();
// Return as array
var arrDate = extractDate(x[i].innerText);
console.log(strDate);
}
<ul id="target">
<li>
Friday, January 1, 2008 - 6:53pm
</li>
<li>
Monday, November 13, 2008 - 3:12pm
</li>
<li>
Friday, November 1, 2008 - 6:53pm
</li>
</ul>
Uses momentjs is one solution:
const test1 = 'Thursday, November 13, 2008 - 3:12pm' // 11/13/2008 is not Monday
const test2 = 'Saturday, November 1, 2008 - 6:53pm' // 11/01/2008 is not Friday
const moment1 = moment(test1, 'dddd, MMMM D, YYYY - h:mma')
const moment2 = moment(test2, 'dddd, MMMM D, YYYY - h:mma')
console.log(moment1.format('dddd, MMMM D, YYYY - h:mma'), moment1.toDate().getTime())
console.log(moment2.format('dddd, MMMM D, YYYY - h:mma'), moment2.toDate().getTime())
const invalid = 'Monday, November 13, 2008 - 3:12pm'
console.log('Invalid Date String', moment(invalid, 'dddd, MMMM D, YYYY - h:mma'))
<script src="https://unpkg.com/moment@2.29.1/moment.js"></script>
You can easily get all data as
function getDate(str) {
const [, day, month, date, year] = str.match(/(\w+), (\w+) (\d+), (\d+)/);
return { day, month, date, year };
}
console.log(getDate("Monday, November 13, 2008 - 3:12pm"));
console.log(getDate("Friday, November 1, 2008 - 6:53pm"));
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you want to get particularly the date 13 or 1 then you can do as
function getDate(str) {
const [, day, month, date, year] = str.match(/(\w+), (\w+) (\d+), (\d+)/);
return { day, month, date, year };
}
const date = getDate("Monday, November 13, 2008 - 3:12pm");
console.log(+date.date);
// or
// console.log(parseInt(date.date));