Sometimes, we want to remove illegal characters from a file name but leave spaces with JavaScript.
In this article, we’ll look at how to remove illegal characters from a file name but leave spaces with JavaScript.
How to remove illegal characters from a file name but leave spaces with JavaScript?
To remove illegal characters from a file name but leave spaces with JavaScript, we can use the string replace
method.
For instance, we write:
const filename = "f?:i/le> n%a|m\e.ext";
const fixedFilename = filename.replace(/[/\?%*:|"<>]/g, '');
console.log(fixedFilename);
to call filename.replace
with a regex that matches all instances of all the characters we want to remove.
Then we remove them by replacing them with empty strings.
Therefore, fixedFilename
is 'file name.ext'
.
Conclusion
To remove illegal characters from a file name but leave spaces with JavaScript, we can use the string replace
method.