Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot save ISO String as a filename due to colons

I have this code which I need to save the result as a filename:

let date = new Date();
date.toISOString(); // for example: "2022-12-19T15:28:46.493Z"

final string would like like this:

let finalStringToSave: "test_2022-12-19T15:28:46.493Z.txt"

When I try to save this string I get an error ...cannot save file.

I have the feeling that this is due to the colons ":" as they are not allowed in a filename.

I've tried to replace all the colons to underscore "_" or dash "-" and I tried this:

let str = finalStringToSave.replace(/:\s*/g, "-"); 
console.log(str);

But for some reason it's not doing the replace.

How can I fix this?

like image 787
zens2022 Avatar asked Oct 22 '25 05:10

zens2022


1 Answers

You can use it like this:

`test_${date.toISOString()}.txt`.replace(/:/g,"_")

Windows seems to have problems saving filenames that contain a ":". The code above replaces every ":" with an "_".

The regex works like this:

  • /: selects the ":" in the string
  • /g is used that all ":" gets replaced, not just the first one

Let me know if it helped.

like image 107
Waleed Ahmad Avatar answered Oct 23 '25 18:10

Waleed Ahmad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!