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

regex - Javascript: How to remove illegal URL characters from a file name? - Stack Overflow

programmeradmin5浏览0评论

How to remove illegal URL characters from a file name but not the dot on file extension? 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. Is it possible?

How to remove illegal URL characters from a file name but not the dot on file extension? 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. Is it possible?

Share Improve this question asked Nov 18, 2015 at 3:09 UnspeakableUnspeakable 2473 silver badges14 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 13

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.]/g

And as hwnd points out, if you don't want to allow other dot characters inside the filename, you can use subtraction:

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

For Windows filenames, I believe a simplified version of the .replace should be
.replace(/[\\/:"*?<>|]/g, '')

发布评论

评论列表(0)

  1. 暂无评论