chrome.downloads API: Replace invalid characters in filename with regex

I am trying to download files with the chrome.downloads.download(...). The filename is given externally, so I don’t know the characters inside. If it contains invalid characters, the function download will throw an error Error: Invalid filename.

  • Is there a regex in JavaScript that replaces all the invalid starting/middle/ending Unicode characters with _ in the filename?

  • Or is there a documentation listing the rules for a filename in Chrome?

  • Is there a way to make Chrome replace invalid characters in my filename, instead of throwing an error?

Chrome disallows more characters than common filesystems (e.g. NTFS), and I am not sure the exact definition of “invalid character” by Chrome. My current regex attempt is

var regex = /^.|.$|[x00-x1f\/:*?"<>|rnu200D]/g;
filename.replaceAll(regex, '_');

But it only covers a few of the invalid Unicode characters.

I avoid using the <a> method to download (i.e. create <a> with href and download attributes, then click on it), because I would like to create subdirectries in the downloads folder.