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:
- No directories. JUST the file name.
- File name needs to be all lowercase.
- Whitespaces need to be replaced with underscores.
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).
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:
- No directories. JUST the file name.
- File name needs to be all lowercase.
- Whitespaces need to be replaced with underscores.
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).
Share Improve this question edited Sep 26, 2008 at 12:32 Remo.D 16.6k6 gold badges49 silver badges79 bronze badges asked Sep 25, 2008 at 0:39 Daddy WarboxDaddy Warbox 4,6089 gold badges43 silver badges58 bronze badges 03 Answers
Reset to default 4If you're in a super-quick hurry, you can usually find acceptable regular expressions in the library at http://regexlib./. Edit to say: Here's one that might work for you:
([0-9a-z_-]+[\.][0-9a-z_-]{1,3})$
And a simple bination of RegExp and other javascript is what I would remend:
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);
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 mon 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= '_'