Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove '-' from a date if it is the last character?

I have a function that receives 3 inputs from the user: year, month and day.

The user can only set the month if the year has been set. The day can also only be set if the month is set.

In the end, the object looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

updatedFields.push({
    id: book.id,
    readIn: `${year}-${month}-${day}`,
});

The problem is that the user is not obliged to inform anything. So if it just informs the year and month or just the year, I’ll have something like:

"2020--" // if he only enters the year
"2021-10-" // if he enters the year and month
"2022-03-13" // if it enters year, month and day

The question is: how do I remove the excess - dashes?

>Solution :

Construct an array from the possible values, filter out those that don’t exist, then join it by the separator.

readIn: [year, month, day].filter(Boolean).join('-')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading