format string into date 5/11/2022 in the moste concise way in javascript

You can use the Date() constructor to create a new date object, and then use appropriate methods to format the output string:

index.tsx
const dateString = '5/11/2022';
const [month, day, year] = dateString.split('/');
const date = new Date(year, month - 1, day);
const formattedDate = date.toLocaleDateString('en-US');

console.log(formattedDate); // "5/11/2022"
227 chars
7 lines

In the code snippet above, we first split the input string into its components (month, day, and year) using the split() method. We then create a new Date() object by passing in the year, month, and day as separate arguments. Note that we subtract 1 from the month value, because JavaScript's Date() constructor expects the month value to be a zero-based index (i.e., January is 0, February is 1, etc.).

Finally, we format the date string using the toLocaleDateString() method, passing in the "en-US" locale to ensure that the date is formatted using the U.S. date format (month/day/year).

This approach is concise, because it combines several steps into a single block of code, using array destructuring to extract the month, day, and year values from the input string, and the toLocaleDateString() method to handle the date formatting.

gistlibby LogSnag