【问题标题】:Convert a Sentence to InitCap / camel Case / Proper Case将句子转换为 InitCap / camel Case / Proper Case
【发布时间】:2013-11-08 16:02:07
【问题描述】:

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

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() => 你好世界

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

【问题讨论】:

    标签: javascript regex string camelcasing


    【解决方案1】:

    你可以试试:

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

    【讨论】:

    • 兄弟,你的按键速度很快,也很准确。我试过你的代码DEMO
    【解决方案2】:

    如果您想使用撇号/破折号来说明名称,或者如果在句子之间的句点之后可能会省略空格,那么您可能需要使用 \b(beg 或单词结尾)而不是 \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。请进来。

    【讨论】:

    • ...但接受你永远不会 100% 正确的事实。当你进入人们的名字时,所有的赌注都被取消了。我知道一个人的姓氏(姓氏)写得正确时是d'Ellerba,但它几乎总是以D'EllerbaD'ellerbaDellerba出现——搜索时我还发现有人叫Dell'Erba
    【解决方案3】:
    str="hello";
    init_cap=str[0].toUpperCase() + str.substring(1,str.length).toLowerCase();
    
    alert(init_cap);
    

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

    【讨论】:

    • 您似乎误解了要求,例如您的解决方案将为hEllo woRld how aRe you 输出Hello world how are you,而它应该输出Hello World How Are You
    【解决方案4】:

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

    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 !

    【讨论】:

      猜你喜欢
      • 2011-05-08
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多