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

Is there a way to get substrings of Javascript strings without explicitly calling length, like C# Range?

Currently if a string is not "known" (or causes side-effect), we need to store it into a variable in order to get n characters from the beginning and 2 lines are needed:

const str = new Date().toISOString();
return str.substring(0, str.length - 1);

// This can be done in one line but the expression is evaluated twice and there's a repetition:
return new Date().toISOString().substring(0, new Date().toISOString().length - 1);

Is there a "clever" way we can do that in one line, like C# Range operator?

return new DateTimeOffset().ToString("o")[..^1];

Note: I know internally length is probably called. This is not a question for optimization but a way to write shorter (and hopefully, clearer) code.

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

>Solution :

You mean slice?

console.log(new Date().toISOString().slice(0,-1))
console.log(new Date().toISOString().slice(11,-5))
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