Reputation: 247
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
Reputation: 1376
For Windows filenames, I believe a simplified version of the .replace should be
.replace(/[\\/:"*?<>|]/g, '')
Upvotes: 4
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