Skip to content

Instantly share code, notes, and snippets.

@ivanionut
Forked from JamoCA/sanitizeFileName.cfm
Last active August 29, 2015 14:19
Show Gist options
  • Save ivanionut/3fc1c92d8133082689ae to your computer and use it in GitHub Desktop.
Save ivanionut/3fc1c92d8133082689ae to your computer and use it in GitHub Desktop.
ColdFusion UDF to sanitize filename & remove illegal characters & symbols that are incompatible/invalid when used with different languages, OS and devices.
<cfscript>
/* 3/18/2015 sanitizeFileName()
Pass filename, list of options (optional), replacementCharacter (default="") */
function sanitizeFileName(s){
var e = trim(listLast(trim(s), "."));
var rules = "";
var replacementCharacter = "";
if(ArrayLen(Arguments) GTE 2) { rules = Arguments[2];}
if(ArrayLen(Arguments) GTE 3 AND LEN(trim(Arguments[3]))) { replacementCharacter = Arguments[3];}
s = trim(s);
if (ListLen(s,".") IS 1){
s = "";
} else {
s = left(s, len(s) - len(e)-1);
e = rereplace(e, "[^A-Za-z0-9]", "", "all");
s = rereplace(s, "[^A-Za-z0-9\-_]", replacementCharacter, "all");
}
if (listfindnocase(rules, "convertspacestounderscores")){
s = rereplace(s, " ", "_", "all");
} else if (listfindnocase(rules, "convertspacestodashes")){
s = rereplace(s, " ", "-", "all");
}
if (listfindnocase(rules, "convertdashtounderscore")){
s = rereplace(s, "[\-]", "_", "all");
} else if (listfindnocase(rules, "convertunderscoretodash")){
s = rereplace(s, "[\_]", "-", "all");
} else {
if (listfindnocase(rules, "nodash")){
s = rereplace(s, "[\-]", replacementCharacter, "all");
}
if (listfindnocase(rules, "nounderscore")){
s = rereplace(s, "[\_]", replacementCharacter, "all");
}
}
if (listfindnocase(rules, "forcelowercase")){
s = lcase(s);
} else if (listfindnocase(rules, "forceuppercase")){
s = ucase(s);
}
if (NOT LEN(e) OR NOT LEN(S)){
s = "";
} else {
s = s & "." & lcase(e);
}
return s;
}
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment