最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - RegExp for clean file and folder names - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Oct 7, 2010 at 11:48 YensYens 9254 gold badges12 silver badges24 bronze badges 3
  • 1 Have you tried anything? It is only good for you if you learn regular expressions and this is a basic one. This should be a start: regular-expressions.info – Felix Kling Commented Oct 7, 2010 at 11:51
  • I strongly guess this is a FAQ! Just search for [regex] +filename +validate – splash Commented Oct 7, 2010 at 11:52
  • @Felix Kling thanks for the tip! don't have the time learn it at the moment but I will in the near future :) – Yens Commented Oct 7, 2010 at 12:06
Add a comment  | 

4 Answers 4

Reset to default 12

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

This seems quite straightforward:

/^[\w.-]+$/

Useful tutorial

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

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

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

评论列表(0)

  1. 暂无评论