Skip to content

Instantly share code, notes, and snippets.

@erkobridee
Last active August 9, 2023 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erkobridee/df4809d8b017329687499f74a308ce88 to your computer and use it in GitHub Desktop.
Save erkobridee/df4809d8b017329687499f74a308ce88 to your computer and use it in GitHub Desktop.
// it also supports extensions like .tar.gz
export const getFileExtension = (filename: string) =>
(filename.match(/(\.([^.]*?)(\.([^.]*?))?)(?=\?|#|$)/) || [])[1] ?? "";
//---===---//
/* eslint-disable */
const SANITIZE_FILENAME_REGEXP = {
NO_LEFT_SPACES: /^\s+/g,
NO_SEQ_DOTS: /\.+/g,
ILLEGAL: /[\/\?<>\\:\*\|"]/g,
CONTROL: /[\x00-\x1f\x80-\x9f]/g,
RESERVED: /^\.+$/,
WINDOWS_RESERVED: /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,
WINDOWS_TRAILING: /[\. ]+$/,
};
/* eslint-enable */
interface SanitizeFilenameOptions {
replacement?: string;
maxLength?: number;
}
export const sanitizeFilename = (
input: string,
{ replacement = "", maxLength = 255 }: SanitizeFilenameOptions = {}
) => {
if (input.length === 0) {
throw new Error("The input needs to be defined");
}
const {
NO_LEFT_SPACES,
NO_SEQ_DOTS,
ILLEGAL,
CONTROL,
RESERVED,
WINDOWS_RESERVED,
WINDOWS_TRAILING,
} = SANITIZE_FILENAME_REGEXP;
let sanitized = input
.split("?")[0]
.split("#")[0]
.replace(NO_SEQ_DOTS, ".")
.replace(NO_LEFT_SPACES, replacement)
.replace(ILLEGAL, replacement)
.replace(CONTROL, replacement)
.replace(RESERVED, replacement)
.replace(WINDOWS_RESERVED, replacement)
.replace(WINDOWS_TRAILING, replacement);
if (sanitized.length <= maxLength) {
return sanitized;
}
const fileExtension = getFileExtension(sanitized);
const fileExtensionLength = fileExtension.length;
let endIndex = maxLength - 1;
if (fileExtensionLength === 0) {
return sanitized.slice(0, endIndex);
}
// the latest index is equals to length -1 and we also need to consider the . char before the extension
endIndex = maxLength - (fileExtensionLength + 2);
return `${sanitized.slice(0, endIndex)}.${fileExtension}`;
};
export default sanitizeFilename;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment