How to extract date from string using JavaScript?
The best way is to use a regex to extract a date from a string in JavaScript. First, need Regular expression and then match it with given strings. If matched the split store the values.
Example code regex to extract date from string
Here is the complete code on how to extract a date from a string. We created a function for it, just pass the string and function return the date data.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function getDate(d)
{
var day, month, year;
result = d.match("[0-9]{2}([\-/ \.])[0-9]{2}[\-/ \.][0-9]{4}");
if(null != result) {
dateSplitted = result[0].split(result[1]);
day = dateSplitted[0];
month = dateSplitted[1];
year = dateSplitted[2];
}
result = d.match("[0-9]{4}([\-/ \.])[0-9]{2}[\-/ \.][0-9]{2}");
if(null != result) {
dateSplitted = result[0].split(result[1]);
day = dateSplitted[2];
month = dateSplitted[1];
year = dateSplitted[0];
}
if(month>12) {
aux = day;
day = month;
month = aux;
}
return year+"/"+month+"/"+day;
}
alert(getDate('test 2021/01/01 this'))
</script>
</head>
<body>
</body>
</html>
Output:
Q: How to Extract multiple dates from a string in JavaScript with Regex?
Answer: Let’s extract the date pattern from the string in JS. This example code is used as a complex string.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
const strings = [
"From2017-01-01to2017-12-31_custom_EquityPurchaseAgreementMember_custom_FirstPaymentMember_currency_CNY",
"From2016-01-01to2016-12-31",
"From2017-01-01to2017-12-31_custom_EquityPurchaseAgreementMember_custom_FirstPaymentMe",
"AsOf2017-12-31"
];
let pattern = /\d{4}\-\d{2}\-\d{2}/g;
strings.forEach((s) => {
console.log(s.match(pattern));
});
</script>
</head>
<body>
</body>
</html>
Output:
Do comment if you have another way to do it or any suggestions.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version