破折号或斜杠后将字符串转换为标题大小写

问题描述 投票:1回答:2

我使用这个常用函数将我的大多数列表项转换为标题大小写,没有任何问题。我发现有一个地方需要改进,当中间有一个破折号或斜线时,我希望下一个字母大写。

例如西班牙裔/拉丁裔应该是西班牙裔/拉丁裔。基本上大写第一个字母或由符号或空格进行。

当前代码:

function toTitleCase(str) {
    return str.toLowerCase().replace(/(?:^|\s)\w/g, function (match) {
        return match.toUpperCase();
    });
}
javascript string capitalization capitalize
2个回答
3
投票

只需更改你的空白\s的捕获,成为一类字符是空格,连字符或斜线[\s-/](以及你想要的任何其他东西)

function toTitleCase(str) {
    return str.toLowerCase().replace(/(?:^|[\s-/])\w/g, function (match) {
        return match.toUpperCase();
    });
}

console.log(toTitleCase("test here"));
console.log(toTitleCase("test/here"));
console.log(toTitleCase("test-here"));

2
投票

只需在正则表达式/(?:^|\s|\/|\-)\w/g中添加或条件

function toTitleCase(str) {
    return str.toLowerCase().replace(/(?:^|\s|\/|\-)\w/g, function (match) { 
      return match.toUpperCase();  
    });
}


console.log(toTitleCase('His/her new text-book'))
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.