skip to Main Content

var string = '1: Mode: SOME Date range: 01/01/2018-31/12/2018 User: HANS'

I would like to get a date from the above string, remove all the other content and return like the below:

['2018-01-01', '2018-12-31', '201801', '201812']

Basically, YYYY-MM-DD, YYYY-MM-DD, YYYMM, YYYYMM.

I have tried the following but couldn’t progress more:

var res = string.match(/d{2}([/.-])d{2}1d{4}/g);

=> ['01/01/2018', '31/12/2018']

Then another function is to get the YYYYMM part.

var arr = res[0].split("-");
return arr[0]+arr[1];
=> '201801'

Is it possible to get the four elements in a single array in an efficient way?

Thanks in advance!

6

Answers


  1. I would do it in two steps. Find the dates, then format them.

    const formatDateParts = (string) => {
        const [day, month, year] = string.split('/');
        return [[year, month, day].join('-'), `${year}${month}`];
    };
    
    const [_, date1, date2] = string.match(/(d{2}/d{2}/d{4})-(d{2}/d{2}/d{4})/);
    
    const [date1Format, date1Condensed] = formatDateParts(date1);
    const [date2Format, date2Condensed] = formatDateParts(date2);
    
    const result = [date1Format, date2Format, date1Condensed, date2Condensed];
    
    Login or Signup to reply.
  2. I know this has already been answered, but this answer may be more readable / clean

    var string = "1: Mode: SOME Date range: 01/01/2018-31/12/2018 User: HANS";
    // Get each date
    var dates = string.match(/(d+/){2}d+/g);
    // Split each date into day, month & year
    dates = dates.map(i => i.split("/"));
    // Format into desired format
    // ['2018-01-01', '2018-12-31', '201801', '201812']
    dates = [
        `${dates[0][2]}-${dates[0][1]}-${dates[0][0]}`,
        `${dates[1][2]}-${dates[1][1]}-${dates[1][0]}`,
        `${dates[0][2]}${dates[0][1]}`,
        `${dates[1][2]}${dates[1][1]}`,
    ];
    
    Login or Signup to reply.
  3. let data = "1: Mode: SOME Date range: 01/01/2018-31/12/2018 User: HANS"
    
    let regex = /(d{2}/d{2}/(19|20)d{2})-(d{2}/d{2}/(19|20)d{2})/
    
    res = data.match(regex)
    let x = res[1].split("/")
    let y = res[3].split("/")
    [res[1].replaceAll("/", "-"), res[3].replaceAll("/", "-"), x[2] + x[1], y[2] + y[1]]
    
    Login or Signup to reply.
  4. const string = '1: Mode: SOME Date range: 01/01/2018-31/12/2018 User: HANS';
    
    // Extract the date range using regex
    const dateRangeRegex = /(d{2}/d{2}/d{4})-(d{2}/d{2}/d{4})/;
    const dateRangeMatch = string.match(dateRangeRegex);
    const startDate = dateRangeMatch[1];
    const endDate = dateRangeMatch[2];
    
    // Convert the start and end dates to the desired format
    const startDateFormatted = startDate.split('/').reverse().join('-');
    const endDateFormatted = endDate.split('/').reverse().join('-');
    
    // Extract the year and month from the start and end dates
    const yearMonthStart = startDate.substring(6, 10) + startDate.substring(3, 5);
    const yearMonthEnd = endDate.substring(6, 10) + endDate.substring(3, 5);
    
    // Create the resulting array
    const result = [startDateFormatted, endDateFormatted, yearMonthStart, yearMonthEnd];
    
    console.log(result);
    Login or Signup to reply.
  5. This should fix your issue.

    Code:

    let theString = '1: Mode: SOME Date range: 01/01/2018-31/12/2018 User: HANS';
    
    let dateFilter = theString.match(/bd{2}/d{2}/d{4}b/g);
    
    let dates = dateFilter.map((date) => {
        let parts = date.split('/');
        let formattedDate = [parts[2], parts[1], parts[0]].join('-');
        let yearMonth = parts[2] + parts[1];
        return [formattedDate, yearMonth];
    }).flat();
    
    console.log(dates);
    
    Login or Signup to reply.
  6. But if you want, you can extract everything in one step.

    function extractDates (string) {
        let result = /^.*(?<!d)(d{2})/(d{2})/(d{4})-(d{2})/(d{2})/(d{4})(?!d).*$/.exec(string);
        return result? [
            `${result[3]}-${result[2]}-${result[1]}`,
            `${result[6]}-${result[5]}-${result[4]}`,
            `${result[3]}${result[2]}`,
            `${result[6]}${result[5]}`
        ]: null;
    }
    
    let string = '1: Mode: SOME Date range: 01/01/2018-31/12/2018 User: HANS';
    console.log(extractDates(string));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search