Skip to content

Instantly share code, notes, and snippets.

@tennox
Created November 29, 2021 14:43
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 tennox/003b0284e507b590d12ecdb2867c3692 to your computer and use it in GitHub Desktop.
Save tennox/003b0284e507b590d12ecdb2867c3692 to your computer and use it in GitHub Desktop.
Sanitize string & filename
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