Replace underscores/snake case and capitalize/title case page title w/ Ember helper

Ran into a situation where my page titles are generated from snake cased terms in JSON. Needed to remove the underscores and capitalize the words while leaving stop words lowercase.

In the event you need to do this, here is how to make it happen.

// app/helpers/title-case.js

import { helper } from '@ember/component/helper';
import { capitalize } from '@ember/string';

const wordsNotToCapitalize = [
    'a',
    'an',
    'and',
    'is',
    'the',
];

export default helper(function titleCase([title]) {
    return title
        .split(/_+/g)
        .map((word, index) => {
            if (index > 0 && wordsNotToCapitalize.includes(word)) {
                return word;
            }

            return capitalize(word);
        })
        .join(' ');
});

It’s now a helper you can use in templates like any other Ember Helper.

In my case:

{{title-case this.model.disciplines}}

Cheers! :beers:

2 Likes