Action
Sanitize Filename
Posted by oktobertrey,
Last update
about 16 hours ago
Replaces invalid filename characters (I tried to only allow characters that are valid on both Windows and MacOS file systems) with underscores. This will work on just the text that is currently selected, or on the entire draft if there’s no selection.
Steps
-
script
// See online documentation for examples // https://docs.getdrafts.com/docs/actions/scripting // === CONFIGURATION === const sanitizationCharacter = '_'; // Change this to '-' or any other safe character // Allowed characters on both macOS and Windows const allowedCharactersPattern = new RegExp(`[^A-Za-z0-9 !#$%&'()+,\\-\\.\\;=@[\\]^_\`{}~]`, 'g'); // Get selected text or full draft let input = editor.getSelectedText(); if (!input || input.trim() === "") { input = editor.getText(); } // Replace invalid characters with the chosen replacement character let output = input.replace(allowedCharactersPattern, sanitizationCharacter); // Clean up redundant replacement characters (e.g., "__" => "_") const escapedSanitizationCharacter = sanitizationCharacter.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); const mergeDuplicateCharactersPattern = new RegExp(`${escapedSanitizationCharacter}{2,}`, 'g'); output = output .replace(mergeDuplicateCharactersPattern, sanitizationCharacter) // collapse repeated .replace(new RegExp(`^${escapedSanitizationCharacter}+|${escapedSanitizationCharacter}+$`, 'g'), '') // trim edges .trim(); // trim whitespace // Replace the selected text (or whole draft) with sanitized version if (editor.getSelectedText()) { editor.setSelectedText(output); } else { editor.setText(output); }
Options
-
After Success Default Notification Info Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.