Code available on npm and GitHub
Each year brings new ways to add JS to HTML. One modern option is:
<script type="module">
import { toTitleCase } from './to-title-case.js'
toTitleCase('make me a title') //→ Make Me a Title
</script>
Or for a classic, global vibe, you can try:
<script src="to-title-case.cjs"></script>
<script>
toTitleCase('make me a title') //→ Make Me a Title
</script>
Install with npm install @gouch/to-title-case then import:
import { toTitleCase } from '@gouch/to-title-case'
toTitleCase('make me a title') //→ Make Me a Title
The script defines the function toTitleCase(), which applies title case rules
to an input string. For best results, input is assumed to be sentence case or naive title
case.
toTitleCase('make me a title') //→ Make Me a Title
The lowercase word list can be replaced with your own:
toTitleCase('make me a title', { lowercase: ['me'] }) //→ Make me A Title
Title case, or headline case, is a convention for formatting the titles of articles and the headings within. It does basically amount to capitalizing each word, but with a few lowercase exceptions that look odd if you miss them.
Most well-known style guides follow dynamic rules that switch depending on how a word is being used in context. Evaluating grammar is outside the scope of a small script, so this script follows static, consistent rules. Those rules are a close match to the New York Times style guide.
I built this in response to John Gruber’s post in 2008.
Matt Belz maintains an excellent site documenting the differing rules of well-known style guides.
If you’re stuck with uppercase input, it is technically possible to brute force it by applying a lowercase transform:
toTitleCase('CNN REPORTS ON NASA CENTER IN HOUSTON, TX'.toLowerCase())
//→ Cnn Reports on Nasa Center in Houston, Tx
But consider carefully before doing this. As frustrating as data stuck in uppercase might be, turning acronyms into distracting typos might be worse.
Version 2 assigned itself as a method on the built-in String object. If you want to restore that behavior, you can use this code:
String.prototype.toTitleCase = function (options) {
return toTitleCase(this, options)
}
'make me a title'.toTitleCase() //→ Make Me a Title
Note: arrow functions won’t work here since they change how this is handled.