简体   繁体   English

创建一个使用React Native的``标题大小写''的函数

[英]Creating a function to use React Native 'title case'

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. 当用户转到输入(providerName)时,输入不会自动将首字母大写。 I'm not sure why. 我不知道为什么。 The file is called detail.ts and it sits under the util/scenes folder. 该文件称为detail.ts,位于util / scenes文件夹下。 So using "Scenes.detail" should call the function. 因此,使用“ Scenes.detail”应调用该函数。 Unless my function is wrong. 除非我的功能不对。 Also, in scenes/detail.ts there is an export default for titleCase. 另外,在scenes / detail.ts中,有一个titleCase导出默认值。 It wasn't there earlier and so I added it but it still is not working as I would like. 它不存在,所以我添加了它,但是它仍然无法正常运行。

在任何用空格分隔单词的字符串str上尝试str.replace(/\\b(\\w)/g, k => k.toUpperCase())

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM