Skip to content

Instantly share code, notes, and snippets.

@vanadium23
Created June 19, 2023 14:46
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 vanadium23/70d3645d424f7792f9bd68aacc0d86b0 to your computer and use it in GitHub Desktop.
Save vanadium23/70d3645d424f7792f9bd68aacc0d86b0 to your computer and use it in GitHub Desktop.
var illegalRe = /[\/\?<>\\:\*\|"]/g;
var controlRe = /[\x00-\x1f\x80-\x9f]/g;
var reservedRe = /^\.+$/;
var windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;
var windowsTrailingRe = /[\. ]+$/;
function truncate(str, num) {
if (str.length > num) {
return str.slice(0, num) + "...";
} else {
return str;
}
}
function sanitize(input, replacement) {
if (typeof input !== 'string') {
throw new Error('Input must be string');
}
var sanitized = input
.replace(illegalRe, replacement)
.replace(controlRe, replacement)
.replace(reservedRe, replacement)
.replace(windowsReservedRe, replacement)
.replace(windowsTrailingRe, replacement);
return truncate(sanitized, 255);
}
module.exports = function (input, options) {
var replacement = (options && options.replacement) || '';
var output = sanitize(input, replacement);
if (replacement === '') {
return output;
}
return sanitize(output, '');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment