-2

I need a regular expression who substitute the third slash in to a space.

To be more specific I've this case: A Date = 28/11/2022/11:40 and I wish that the date will be in this format 28/11/2022 11:40.

As written before I expect this way 28/11/2022 11:40 ( without the slash between the time and the date )

Andy A.
  • 1,392
  • 5
  • 15
  • 28
Xbox user
  • 1
  • 3
  • 1
    If it's always dd/mm/yyyy then use `substring` to replace that character: https://stackoverflow.com/a/1431113/2181514 – freedomn-m Nov 28 '22 at 10:47

1 Answers1

1

There are again a few ways to do what you need.

You can use String.prototype.substring if the date is always in the same format or you can use a regular expression to handle other cases. If you are working with dates a lot in your application I'd recommend a simple library like dayjs. It's lightweight and you could use .format('DD/MM/YYYY HH:mm') method to format your date.

const date = '28/11/2022/11:40';

const formatDate = (date) => {
    return `${date.substring(0, 10)} ${date.substring(11)}`;
};

const formatDateWithRegex = (date) => {
    return date.replace(/^(\d{1,2}\/\d{1,2}\/\d{4})\/(\d{1,2}:\d{2})$/, "$1 $2");
};

console.log('Without RegExp: ',formatDate(date));
console.log('With RegExp:', formatDateWithRegex(date));

The regex I've used here is probably suboptimal but it groups your MM/DD/YYYY date and HH:mm as a separate groups and then returns them with a space being the separator ($1 - first group, $2 - second group).

AbsoluteZero
  • 401
  • 7