What's the (JavaScript) Regular Expression I should use to ensure a string is a valid file name?

StackOverflow https://stackoverflow.com/questions/130837

  •  02-07-2019
  •  | 
  •  

Question

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:

  1. No directories. JUST the file name.
  2. File name needs to be all lowercase.
  3. 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).

Was it helpful?

Solution

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);

OTHER TIPS

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.

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= '_'

I would check out the RegEx Library.

You can pick from any number of preconfigured regular expressions of varying degrees of robustness to suit your needs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top