简体   繁体   English

Javascript:如何从文件名中删除非法URL字符?

[英]Javascript: How to remove illegal URL characters from a file name?

How to remove illegal URL characters from a file name but not the dot on file extension? 如何从文件名中删除非法URL字符,但不删除文件扩展名上的点? Is there a way to do this? 有没有办法做到这一点? Currently I have this 目前我有这个

fileName = "I am a file name + two.doc"
fileName.replace(/[^a-zA-Z0-9-_]/g, ''); // regex that removes illegal characters

But it also removes the . 但它也删除了。 on the .doc I want something that will remove illegal characters except the file extension. 在.doc我想要的东西将删除除文件扩展名之外的非法字符。 Is it possible? 可能吗?

Add the . 添加. literal as well then, \\. 文字,然后, \\. :

var fileName = "I am a file name + two.doc";
fileName.replace(/[^a-zA-Z0-9-_\.]/g, ''); // 'Iamafilenametwo.doc'

It's worth pointing out that the . 值得指出的是. character in a regular expression will match any single character except the newline character . 正则表达式中的字符将匹配除换行符之外的任何单个字符 Therefore you needed to escape the character in order for it to match the literal character, \\. 因此,您需要转义字符才能使其与文字字符\\.匹配\\.

Also, \\w is equivilant to [A-Za-z0-9_] , therefore you could shorten your expression to: 此外, \\w等同于[A-Za-z0-9_] ,因此您可以将表达式缩短为:

/[^\w.]/g

And as hwnd points out , if you don't want to allow other dot characters inside the filename, you can use subtraction: 正如hwnd所指出的 ,如果你不想在文件名中允许其他点字符,你可以使用减法:

.replace(/(?!\.[^.]+$)\.|[^\w.]+/g, '')

For Windows filenames, I believe a simplified version of the .replace should be 对于Windows文件名,我相信.replace的简化版本应该是
.replace(/[\\\\/:"*?<>|]/g, '')

在此输入图像描述 在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM