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?
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, '')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.