admin管理员组文章数量:1430083
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= '_'
本文标签:
版权声明:本文标题:regex - What's the (JavaScript) Regular Expression I should use to ensure a string is a valid file name? - Stack Overflo 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745540388a2662466.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论