Reputation: 6896
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?
Upvotes: 36
Views: 47047
Reputation: 13159
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, '-');
Upvotes: 8
Reputation: 31682
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);
Upvotes: 82
Reputation: 742
Add the '\s' whitespace to your exclusion.
str = str.replace(/([^a-z0-9\s]+)/gi, '-');
Upvotes: 1
Reputation: 7593
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 -------^
Upvotes: 8