Created
November 29, 2021 14:43
-
-
Save tennox/003b0284e507b590d12ecdb2867c3692 to your computer and use it in GitHub Desktop.
Sanitize string & filename
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
const _ = require('lodash') | |
const sanitize = str => _.chain(str) | |
.replace(/[^A-Za-z0-9&.-]/g, '-') // sanitise via whitelist of characters | |
.replace(/-(?=-)/g, '') // remove repeated dashes - https://regexr.com/6ag8h | |
.trim('-') // trim any leading/trailing dashes | |
.truncate({ | |
length: 40, // max length | |
omission: '-' // when the string ends with '-', you'll know it was truncated | |
}) | |
.value() | |
const sanitizeFilename = filename => { | |
// sanitize filename but keep extension | |
const filename_parts = filename.split('.') | |
const ext = _.slice(filename_parts, filename_parts.length-1) | |
const filename_main = _.join(_.dropRight(filename_parts), '.') | |
return sanitize(filename_main) + '.' + ext | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment