Created
June 19, 2023 14:46
-
-
Save vanadium23/70d3645d424f7792f9bd68aacc0d86b0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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