Skip to content

Instantly share code, notes, and snippets.

@ali-master
Created October 13, 2025 06:31
Show Gist options
  • Save ali-master/0123db4057d17dabf03ed9f1d7a7f00f to your computer and use it in GitHub Desktop.
Save ali-master/0123db4057d17dabf03ed9f1d7a7f00f to your computer and use it in GitHub Desktop.
Converts a string into a file-safe string by replacing or removing characters that are not safe for filenames on most filesystems.
/**
* Converts a string into a file-safe string by replacing or removing
* characters that are not safe for filenames on most filesystems.
* - Replaces spaces and unsafe characters with underscores.
* - Removes or replaces reserved/special characters.
* - Trims leading/trailing underscores and dots.
*/
export function toFileSafeString(input: string): string {
return input
.normalize("NFKD") // Normalize unicode
.replace(/[\u0300-\u036f]/g, "") // Remove diacritics
.replace(/[^a-zA-Z0-9._-]/g, "_") // Replace unsafe chars with _
.replace(/_+/g, "_") // Collapse multiple underscores
.replace(/^[_.]+|[_.]+$/g, "") // Trim leading/trailing _ or .
.slice(0, 255); // Limit to 255 chars (common FS limit)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment