toSafeFilename
Converts a string to a safe filename by removing or replacing invalid characters.
1/**
2 * Converts a string to a safe filename by removing or replacing invalid characters.
3 *
4 * @param name - The input string to convert.
5 * @param replacement - The character to replace invalid characters with (default: "_").
6 * @returns A sanitized string safe to use as a filename.
7 */
8export function toSafeFilename(name: string, replacement = '_'): string {
9 return name
10 .trim()
11 .replace(/[<>:"/\\|?*\x00-\x1F]/g, replacement) // Windows reserved characters
12 .replace(/[\u{0080}-\u{FFFF}]/gu, replacement) // Control and unicode chars
13 .replace(/[\s.]+$/g, '') // Remove trailing spaces or dots
14 .substring(0, 255); // Limit length for most filesystems
15}
Cross-Platform Compatibility
Removes or replaces characters that are disallowed on major operating systems (e.g., Windows, macOS, Linux), ensuring wide filesystem support.
Customizable Replacement Character
Supports a configurable replacement for invalid characters, offering flexibility in naming schemes.
Unicode and Control Character Filtering
Replaces problematic Unicode ranges and control characters that might corrupt file systems or cause encoding issues.
Trailing Cleanup
Eliminates trailing whitespace and dots which can be problematic in certain environments (e.g., Windows Explorer).
Length-Safe Output
Truncates the resulting filename to a maximum of 255 characters, a common upper bound in modern filesystems.
Tests | Examples
1test('toSafeFilename - replaces unsafe characters', () => {
2 expect(toSafeFilename('report:2023/12/31')).toBe('report_2023_12_31');
3});
4
5test('toSafeFilename - trims trailing dots and spaces', () => {
6 expect(toSafeFilename('file name. ')).toBe('file name');
7});
8
9test('toSafeFilename - handles unicode and control chars', () => {
10 expect(toSafeFilename('emoji💥test\x00file')).toBe('emoji_test_file');
11});
12
13test('toSafeFilename - uses custom replacement', () => {
14 expect(toSafeFilename('path/to\\file', '-')).toBe('path-to-file');
15});
16
17test('toSafeFilename - truncates very long filenames', () => {
18 const long = 'a'.repeat(300);
19 expect(toSafeFilename(long).length).toBeLessThanOrEqual(255);
20});
Common Use Cases
Saving User-Generated Content
Sanitize titles or names submitted by users before saving them as files (e.g., exported reports or images).
Dynamic File Downloads
Convert arbitrary strings (e.g., URLs, form fields) into valid filenames for blob downloads in the browser.
Log File Naming
Create predictable, safe filenames for logs generated by scripts or web apps.
Filesystem Backup Tools
Ensure safe naming when serializing JSON data, web content, or metadata into files or folders.
Filename Normalization in Cross-Platform Applications
Prevent invalid file errors when syncing, exporting, or archiving content across diverse systems.