re: Two string methods every JavaScript developer should know. VIEW POST

FULL DISCUSSION
 

Great post!.

Whenever I'm in a position where I can implement different solutions to the same problem involving strings, I try to follow this decision tree:

desicion tree

I always try to write solutions with as few lines as possible without compromising readability.

For your task, this also works:

> let date = '"2019-08-02T00:00:00.000Z"'
> date.substring(date.indexOf('"') + 1, date.indexOf("T"))
'2019-08-02'
 

Wow this is brilliant, didn't know you could do that in just one line of code. Thanks for sharing Fidel, I appreciate it!

 

If it's a fixed format you can just slice it out without having to spend CPU cycles searching.

const dt = '"2019-08-02T00:00:00.000Z"';
const date = dt.slice(1,11);
console.log(date);

The methods in the article are definitely handy to have in your toolkit though.

 

.slice(), .substr() and .substring() can all achieve this but I agree completely that it should be done with the fixed indexes since its quite apparent the data is all in the same format given his example and glad that my first thought was apparently the most efficient!

edit: turns out substr is non-standard and substring should be used instead

code of conduct - report abuse