A JavaScript method for intelligently converting strings to title case.
Intelligently format your headlines into title case.
<script src="to-title-case.js"></script>
npm install @gouch/to-title-case
and then add require('@gouch/to-title-case')
to your scriptUse the .toTitleCase()
method on strings you want converted to title case:
'Make me a headline'.toTitleCase() // returns: Make Me a Headline
The script assumes input is either sentence case (e.g. To title case for JavaScript) or every-word “title case” (e.g. To Title Case For JavaScript). In both cases, the script will convert the text to To Title Case for JavaScript.
Title case (or headline case) is a convention for formatting the titles of things. It’s often used for the title of articles, but also matters if you mention the title of something in paragraph.
These rules are based on style guides from APA, Chicago, and modern conventions. The result will match general expectations for what a title should look like. Some style guides might state special rules depending on contextual use, but these decisions rely on grammatical understanding, which is beyond the scope of a small script. Your titles will at least be consistent.
* Treating these as small words was inherited from Gruber's implementation. They're likely based on New York Times style. Opinions are welcome on whether these should be removed in a future version.
If you’re stuck with uppercase input, you can get to title case by changing to lowercase first:
'CAPSLOCK FOREVER'.toLowerCase().toTitleCase() // returns: Capslock Forever
// Don’t actually do this until you read the notes below!
Think hard before doing this! As frustrating as all uppercase input can be, acronyms are very common. Turning genuine abbreviations into blatant typos is a worse look than all caps. As an example, this was a real headline from CNN:
PETA: Turkey, TX, change your name
If you brute forced that into title case, you'd wind up with Peta and Tx, which would make Cnn look pretty amateur.
split
instead of replace
. This makes it easier to follow what the script is doing.I built this after reading John Gruber’s explanation of title case.