Reputation: 4598
I'm still learning RegEx at the moment, but for the time being could someone help me out with this? I have a few special requirements for formatting the string:
Shouldn't be hard, but I'm pressed for time and I'm not sure on the 'correct' way to ensure a valid file name (namely I forget which characters were supposed to be invalid for file names).
Upvotes: 2
Views: 3001
Reputation: 5292
If you're in a super-quick hurry, you can usually find acceptable regular expressions in the library at http://regexlib.com/. Edit to say: Here's one that might work for you:
([0-9a-z_-]+[\.][0-9a-z_-]{1,3})$
Upvotes: 4
Reputation: 2636
And a simple combination of RegExp and other javascript is what I would recommend:
var a = "c:\\some\\path\\to\\a\\file\\with Whitespace.TXT";
a = a.replace(/^.*[\\\/]([^\\\/]*)$/i,"$1");
a = a.replace(/\s/g,"_");
a = a.toLowerCase();
alert(a);
Upvotes: 1
Reputation: 536339
If you're taking a string path from the user (eg. by reading the .value of a file upload field), you can't actually be sure what the path separator character is. It might be a backslash (Windows), forward slash (Linux, OS X, BSD etc.) or something else entirely on old or obscure OSs. Splitting the path on either forward or backslash will cover the common cases, but it's a good idea to include the ability for the user to override the filename in case we guessed wrong.
As for 'invalid characters' these too depend on the operating system. Probably the easiest path is to replace all non-alphanumerics with a placeholder such as an underscore.
Here's what I use:
var parts= path.split('\\');
parts= parts[parts.length-1].split('/');
var filename= parts[parts.length-1].toLowerCase();
filename= filename.replace(new RegExp('[^a-z0-9]+', 'g'), '_');
if (filename=='') filename= '_'
Upvotes: 1