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

小提琴

我想要的是

“你好世界”.initCap() => 你好世界

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

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

4

4 回答 4

22

你可以试试:

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

于 2013-11-08T16:03:56.937 回答
2

如果您想用撇号/破折号来说明名称,或者如果在句子之间的句点之后可能会省略空格,那么您可能需要在您的正则表达式将空格、撇号、句号、破折号等后面的任何字母大写。

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。请进来。

于 2018-07-04T22:04:34.843 回答
1
str="hello";
init_cap=str[0].toUpperCase() + str.substring(1,str.length).toLowerCase();

alert(init_cap);

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

于 2017-12-20T22:44:18.510 回答
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 !

于 2022-01-07T00:57:14.000 回答