简体   繁体   中英

Regular expression to remove time from time and date

I am trying to remove time out of a scraped date and time field so i can sort the data by date. Here is a sample of what the data looks like:

12/21/19, 3:02 PM

I am trying to use a regular expression to replace the ", X:XXPM" with nothing and just leave the date but I cannot figure out how to do it. Thank you for your help.

Without a regular expression it is fairly simple, you could just do

let data = "12/21/19, 3:02 PM"
let newData = data.split(",")[0]

If you wish to use a regular expression this would work, but its less readable.

let data = "12/21/19, 3:02 PM"
let newData = data.replace(/,.+/, "");

You won't need regular expression here, just a little substring.

 const dateAndTime = '12/21/19, 3:02 PM'; const dateOnly = dateAndTime.substring(0, dateAndTime.indexOf(',')); console.log(dateOnly);

If your date can appear anywhere in a text, you could use this replace :

 let text = "On a dull day, 12/21/19, 3:02 PM, I was strawling along the beach"; text = text.replace(/\\b((?:\\d\\d\\/){2}\\d\\d)\\W+\\d\\d?:\\d\\d\\s[AP]M\\b/g, "$1"); console.log(text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM