我使用这个常用函数将我的大多数列表项转换为标题大小写,没有任何问题。我发现有一个地方需要改进,当中间有一个破折号或斜线时,我希望下一个字母大写。
例如西班牙裔/拉丁裔应该是西班牙裔/拉丁裔。基本上大写第一个字母或由符号或空格进行。
当前代码:
function toTitleCase(str) {
return str.toLowerCase().replace(/(?:^|\s)\w/g, function (match) {
return match.toUpperCase();
});
}
只需更改你的空白\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"));
只需在正则表达式/(?:^|\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'))