find dates in a string using regex in javascript

To find dates in a string using regex in Javascript, we can use the match() function with a regex pattern that matches date formats.

Here's an example code on how to extract dates in different formats from a string:

index.tsx
const str = "Some random string containing dates like 2021-07-20, 07/20/2021 or July 20, 2021";
const regexPattern = /([0-9]{4}(-[0-9]{2}){2}|[0-9]{2}\/[0-9]{2}\/[0-9]{4}|(January|February|March|April|May|June|July|August|September|October|November|December) [0-9]{1,2},? [0-9]{4})/g;
const dates = str.match(regexPattern);

console.log(dates); // ["2021-07-20", "07/20/2021", "July 20, 2021"]
394 chars
6 lines

In this example, we define a regex pattern using different date formats such as yyyy-mm-dd, mm/dd/yyyy, and month dd, yyyy. We then apply the pattern to the given string using the match() function with the global flag to find all occurrences of dates in the string, and store the results in an array.

The resulting dates array contains all matched date strings in the order they appear in the original string.

Note that the regex pattern used here is not a perfect solution for all date formats and may need to be adjusted depending on the specific use case.

gistlibby LogSnag