Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove illegal characters from a file name but leave spaces

I have the following line of code to remove illegal characters from a file name:

str= str.replace(/([^a-z0-9]+)/gi, '-');

That works fine but it also removes the spaces, how can I only remove the illegal characters but leave the spaces?

like image 256
user3378165 Avatar asked Feb 13 '17 17:02

user3378165


People also ask

What does it mean when it says illegal characters in path?

Cause of the Error MessageThis error occurs when a hyperlink is added which contains special characters.

What file names are illegal in Windows?

Do not use the following reserved names for the name of a file: CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Also avoid these names followed immediately by an extension; for example, NUL. txt is not recommended.


1 Answers

Illegal characters are listed here. To replace them use this regex /[/\\?%*:|"<>]/g like this:

var filename = "f?:i/le>  n%a|m\\e.ext";

filename = filename.replace(/[/\\?%*:|"<>]/g, '-');

console.log(filename);
like image 184
ibrahim mahrir Avatar answered Sep 28 '22 22:09

ibrahim mahrir