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 badges2 Answers
Reset to default 13Add 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, '')