Domanda

I have made this code. I want a small regexp for this.

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

What i want

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

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

my above code gives me solution but i want a better and faster solution with regex

È stato utile?

Soluzione

You can try:

  • Converting the entire string to lowercase
  • Then use replace() method to convert the first letter to convert first letter of each word to upper case

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

Altri suggerimenti

If you want to account for names with an apostrophe/dash or if a space could potentially be omitted after a period between sentences, then you might want to use \b (beg or end of word) instead of \s (whitespace) in your regular expression to capitalize any letter after a space, apostrophe, period, dash, etc.

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

OUTPUT: Hello Billie-Ray O'Malley-O'Rouke.Please Come On In.

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

alert(init_cap);

where str[0] gives 'h' and toUpperCase() function will convert it to 'H' and rest of the characters in the string are converted to lowercase by toLowerCase() function.

If you need to support diacritics, here is a solution:

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 !")

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top