Search code examples
javascriptcapitalizetitle-case

Function to title case a string using javascript


I'm currently working on a fix where there's an existing function that capitalizes each word of the given string. Each value that comes out of that function is later used to validate other logic.

So right now, that function is capitalizing texts in the wrong way. For example internet of things comes out as Internet Of Things and I need it as Internet of Things

This is the function with an adjustment I made, which is basically if the string contains "of" ignore it:

const cleanValue = value
        .replace(/-/g, ' ')
        .split(' ')
        .map((word, i) => {
            return word === 'of' && i != 0 ? word : word[0].toUpperCase() + word.substring(1);
        })
        .join(' ');

But my boss thinks it's a kind of hacky solution and is asking me to look for a better solution, I'm honestly having a hard time trying to fix this in a better way.

Any advice/ideas anyone could provide me on how to improve this?

Thank you!


Solution

  • If you want to ignore some words then you can change your function like this.

    const ignoreWords = ["of", "the", "and"];
    const cleanValue = value
            .replace(/-/g, ' ')
            .split(' ')
            .map((word) => {
                return ignoreWords.includes(word.toLowerCase()) ? word : word[0].toUpperCase() + word.substring(1);
            })
            .join(' ');