Search code examples
javascriptregexfilenames

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


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


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