Creating a function to use React Native 'title case'

2k Views Asked by At

I'm trying to get some input from user to automatically become Title Cased. The code looks solid to me but it seems to not be giving me the output I really want. It is not hooking up the first letter as a uppercase. This is the code to make input title case.

export function titleCase(str: string): string {
    return !str
        ? ""
        : str.toLowerCase()
            .split(" ")
            .map(function(word: string): string {
                return word && word.length > 0 ? word.replace(word[0], word[0].toUpperCase()) : ""
            })
            .join(" ")
}

and then I call it in a view tag like so...

<Text style={styles.providerNameTxt}>
    {Scenes.Detail.titleCase(providerName)}
</Text>
<Text style={styles.providerSpecialtyTxt}>
    {Scenes.Detail.titleCase(providerSpecialty)}
</Text>

Shouldn't this work? When the user goes to input (providerName) the input does not automatically upper case the first letter. I'm not sure why. The file is called detail.ts and it sits under the util/scenes folder. So using "Scenes.detail" should call the function. Unless my function is wrong. Also, in scenes/detail.ts there is an export default for titleCase. It wasn't there earlier and so I added it but it still is not working as I would like.

2

There are 2 best solutions below

2
On
export const toTitleCase = (str) => {
 return str.replace(
     /\w\S*/g,
     (txt) => {
         return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
     }
 );
}
0
On

Try str.replace(/\b(\w)/g, k => k.toUpperCase()) on any string str with words separated by spaces.