将句子转换为 InitCap / 骆驼大小写 / 正确大小写

Convert a Sentence to InitCap / camel Case / Proper Case

本文关键字:大小写 句子 InitCap 转换      更新时间:2023-09-26

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

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());

小提琴

我想要什么

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

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

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

你可以试试:

  • 将整个字符串转换为小写
  • 然后使用 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());

如果要考虑带有撇号/破折号

的名称,或者句子之间的句点后可能会省略空格,那么您可能需要在正则表达式中使用 ''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());

输出:你好比莉-雷·奥马利-奥鲁克,请进来。

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

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

较短的版本

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

如果您需要支持音调符号,这里有一个解决方案:

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 !