将一个句子转换为首字母大写/驼峰式大小写/每个单词首字母大写的格式

6

我已经编写了这段代码,想要一个小的正则表达式。

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
} 
String.prototype.initCap = function () {
    var new_str = this.split(' '),
        i,
        arr = [];
    for (i = 0; i < new_str.length; i++) {
        arr.push(initCap(new_str[i]).capitalize());
    }
    return arr.join(' ');
}
alert("hello world".initCap());

Fiddle

我想要的是:

"hello world".initCap() => Hello World

"hEllo woRld".initCap() => Hello World

我的上面的代码给了我解决方案,但我希望有一个更好、更快的正则表达式解决方案。

5个回答

23
你可以尝试:
  • 将整个字符串转换为小写
  • 然后使用replace()方法将每个单词的首字母转换为大写

str = "hEllo woRld";
String.prototype.initCap = function () {
   return this.toLowerCase().replace(/(?:^|\s)[a-z]/g, function (m) {
      return m.toUpperCase();
   });
};
console.log(str.initCap());


2
兄弟,你的打字速度非常快且准确。我试了一下你的代码演示 - Tushar Gupta - curioustushar
1
这很棒,但我认为你可以使用单词边界\b代替非捕获组(?:^|\s) - undefined
它被用在 OP 吐痰的地方旁边。 - undefined

2

如果您想处理带有撇号/短横线的名称或者句子之间可能省略空格的情况,那么在正则表达式中,您可能需要使用\b(单词的开头或结尾)而不是\s(空格)来将空格、撇号、句点、短横线等后面的字母大写。

str = "hEllo billie-ray o'mALLEY-o'rouke.Please come on in.";
String.prototype.initCap = function () {
   return this.toLowerCase().replace(/(?:^|\b)[a-z]/g, function (m) {
      return m.toUpperCase();
   });
};
alert(str.initCap());

输出:你好 Billie-Ray O'Malley-O'Rouke。请进。


...但要接受你永远不可能完全正确。当涉及到人名时,所有的规则都无效。我认识一个人,他的姓氏在正确书写时是 d'Ellerba,但它几乎总是被写成 D'EllerbaD'ellerba 或者 Dellerba。在搜索时,我还发现有人姓 Dell'Erba - Stephen P

1
str="hello";
init_cap=str[0].toUpperCase() + str.substring(1,str.length).toLowerCase();

alert(init_cap);

其中 str[0] 为 'h',toUpperCase() 函数将其转换为 'H',字符串中的其余字符通过 toLowerCase() 函数转换为小写。


2
看起来你误解了需求,例如你的解决方案会将“hEllo woRld how aRe you”输出为“Hello world how are you”,而实际上应该输出“Hello World How Are You”。 - Arvind Kumar Avinash

1

简短版本

const initcap = (str: string) => str[0].toUpperCase() + str.substring(1).toLowerCase(); 

0
如果您需要支持变音符号,这里有一个解决方案:
function initCap(value) {
  return value
    .toLowerCase()
    .replace(/(?:^|[^a-zØ-öø-ÿ])[a-zØ-öø-ÿ]/g, function (m) {
      return m.toUpperCase();
    });
}

initCap("Voici comment gérer les caractères accentués, c'est très utile pour normaliser les prénoms !")

输出:Voici Comment Gérer Les Caractères Accentués, C'Est Très Utile Pour Normaliser Les Prénoms !


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接