Converting a Title to a Filename in JavaScript

Learn how to convert a title string to a filename in JavaScript using regex.

Created on November 17, 2019.

Here is a function, written for you, that will convert a title to a filename:

const toFilename = (title, ext) => `${title
    .replace(/\s+/g, '-')}.${ext}`

It takes a title, such as 'How Elephants Communicate via Infrasound', and an extension ext, such as 'md' for Markdown, as parameters.

Prepending an absolute or relative path to the output filename is as simple as this:

const filename = `some/path/to/${toFilename(someTitle, someExt)}`

The conversion uses a subset of the Portable Filename Character Set, as in the result contains no capitalization, dots except for delimiting the extension, nor underscores. Why? Personal preference. I find such filenames more navigable in the shell, but you do you.

As for how the function works, first it converts the title to lowercase. Then it replaces all non-alphanumeric characters, including Latin characters—but no whitespace—with nothing, hence no additional parameter in the corresponding replace call. Finally, whitespace is replaced with singular hyphens, and the file extension is concatenated onto the end of the output string.

Note that we make extensive use of string interpolation and regular expressions, which may warrant further reading on your part. I strongly recommend the Regular Expressions Cookbook, since it explains how ECMAScript specifies regex, along with providing plenitudes of JavaScript examples, and even those for seven other programming languages.

© Reese Schultz

My code is released under the MIT license.