Unspeakable
Unspeakable

Reputation: 247

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? 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?

Upvotes: 3

Views: 7010

Answers (2)

Sam
Sam

Reputation: 1376

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

enter image description here enter image description here

Upvotes: 4

Josh Crozier
Josh Crozier

Reputation: 240858

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

Upvotes: 13

Related Questions