Search code examples
javascriptstringsubstring

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.


Solution

  • You mean slice?

    console.log(new Date().toISOString().slice(0,-1))
    console.log(new Date().toISOString().slice(11,-5))