Categories
JavaScript Answers

How to remove illegal characters from a file name but leave spaces with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *