DEV Community

Discussion on: Two string methods every JavaScript developer should know.

Collapse
 
arielrodriguez profile image
Ariel Rodriguez

So far is fine to play a bit with strings. But I'd like to share from my experience, always try to manipulate the objects with their respective API. In this case you are facing a formatted string RFC-3339, and you want to extract its = date-fullyear "-" date-month "-" date-mday

I highly recommend to avoid regex. You should implement Date API, you can achieve easily with 2 lines of code and solid code scalable. As many other answered to you, try to play with Date, as example:

const date = new Date("2019-08-02T00:00:00.000Z")

const fullDate = ${date.getFullYear()}-${date.getMonth()}-${date.getDay()}

Note: toLocaleString is experimental and not stable yet.

You may normalize getMonth and getDay to add 0 to the left when needed.

Collapse
 
_hoyet profile image
Jeremiah Hoyet

They would have still needed to use string.replace to remove the double quotes around the date string, but I prefer your approach of using the Date APIs to ensure you're always going to get the same result.

Collapse
 
p12y profile image
Peter Tyldesley

Not necessarily, you could do it with String.slice or JSON.parse instead.

Collapse
 
losd profile image
Dennis Du Krøger

"Note: toLocaleString is experimental and not stable yet."

For Date (and most other built-in objects)? No it isn't.

developer.mozilla.org/en-US/docs/W...