Yens
Yens

Reputation: 925

RegExp for clean file and folder names

I'm building a File manager with jQuery. Users can create folders and upload files. I need a Regual Expression (javascript) to check if the entered folder-name or the uploaded file-name is web-save. (no special chars or spaces are allowed)

The name should only contain alphanumeric values (a-z,A-Z,0-9), underscores (_) and dashes(-)

Upvotes: 3

Views: 9944

Answers (4)

dreamLo
dreamLo

Reputation: 1860

This is a regex to sanitize Windows files/folders. It will work for POSIX (linux, mac) too, since it's less restrictive.

function sanitizePath (path) {
  return path.replace(/[\\/:*?"<>|]/g, '')
}
console.log(sanitizePath('\\x/:a*b?<>|y'))

Upvotes: 2

user4321031
user4321031

Reputation: 11

function clean(filename) {
filename= filename.split(/[^a-zA-Z0-9\-\_\.]/gi).join('_');
return filename;
};

filename=clean("Vis'it M'ic ro_pole!.pdf");

Upvotes: 1

molokoloco
molokoloco

Reputation: 4602

Don't bother your visitor, do it for him :)

var cleanName = function(name) {
    name = name.replace(/\s+/gi, '-'); // Replace white space with dash
    return name.replace(/[^a-zA-Z0-9\-]/gi, ''); // Strip any special charactere
};

cleanName('C\'est être');

Upvotes: 12

SilentGhost
SilentGhost

Reputation: 319531

This seems quite straightforward:

/^[\w.-]+$/

Useful tutorial

Upvotes: 5

Related Questions