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
Solution 1:
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);
Solution 2:
You are searching for all non numeric and roman letters. If you want to exclude the space from being replaced:
Just add a space to the selection to exclude :)
str= str.replace(/([^a-z0-9 ]+)/gi, '-');
// add a space here -------^
Solution 3:
You can use \W+
\W (non-word-character) matches any single character that doesn't match by \w (same as [^a-zA-Z0-9_]) Source:https://www.ntu.edu.sg/home/ehchua/programming/howto/Regexe.html
str = str.replace(/(\W+)/gi, '-');
Solution 4:
Add the '\s' whitespace to your exclusion.
str = str.replace(/([^a-z0-9\s]+)/gi, '-');
Post a Comment for "Remove Illegal Characters From A File Name But Leave Spaces"