What is filename-reserved-regex?
The filename-reserved-regex npm package provides a regular expression that matches characters that are reserved in filenames across different operating systems. This can be particularly useful for validating filenames or sanitizing them to ensure they are compatible across Windows, macOS, and Unix/Linux systems.
What are filename-reserved-regex's main functionalities?
Validation of filenames
This code sample demonstrates how to use the package to check if a string (which is intended to be used as a filename) contains any reserved characters. The `match` method will return an array of matches if any reserved characters are found, or `null` if the filename is safe to use.
"some*filename?.txt".match(filenameReservedRegex())
Sanitization of filenames
This code sample shows how to sanitize a filename by removing any reserved characters. This is done by replacing any characters that match the regex provided by the package with an empty string, effectively removing them.
"some*filename?.txt".replace(filenameReservedRegex(), '')
Other packages similar to filename-reserved-regex
sanitize-filename
The sanitize-filename package is designed to sanitize a string to ensure it is a valid filename. Unlike filename-reserved-regex, which provides a regex for matching reserved characters, sanitize-filename actively sanitizes the string, making it safe for use as a filename without requiring additional steps.
filenamify
filenamify is another package that converts a string into a valid filename. It goes beyond just removing reserved characters by also truncating the string to a valid length and optionally replacing removed characters with a specified replacement. This makes it a more comprehensive solution compared to filename-reserved-regex, which focuses solely on providing the regex for reserved characters.
filename-reserved-regex
Regular expression for matching reserved filename characters
On Unix-like systems /
is reserved and <>:"/\|?*
as well as non-printable characters \u0000-\u001F
on Windows.
Install
$ npm install filename-reserved-regex
Usage
import filenameReservedRegex, {windowsReservedNameRegex} from 'filename-reserved-regex';
filenameReservedRegex().test('foo/bar');
filenameReservedRegex().test('foo-bar');
'foo/bar'.replace(filenameReservedRegex(), '!');
windowsReservedNameRegex().test('aux');
API
filenameReservedRegex()
Returns a regex that matches all invalid characters.
windowsReservedNameRegex()
Returns an exact-match case-insensitive regex that matches invalid Windows
filenames. These include CON
, PRN
, AUX
, NUL
, COM1
, COM2
, COM3
, COM4
, COM5
,
COM6
, COM7
, COM8
, COM9
, LPT1
, LPT2
, LPT3
, LPT4
, LPT5
, LPT6
, LPT7
, LPT8
and LPT9
.