6

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

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107

5 Answers5

23

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());
nmak18
  • 1,059
  • 8
  • 24
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

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.

RJLyders
  • 353
  • 3
  • 9
  • ...but accept that you'll never be 100% correct. All bets are off when you get into people's names. I know someone whose last-name (family-name) when written properly, is `d'Ellerba` but it almost always comes out as `D'Ellerba` or `D'ellerba` or `Dellerba` -- when searching I also found someone named `Dell'Erba` – Stephen P Aug 29 '18 at 21:13
1
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.

Bishnu Paudel
  • 2,083
  • 1
  • 21
  • 39
  • 2
    It seems you misunderstood the requirement e.g. your solution will output `Hello world how are you` for `hEllo woRld how aRe you` whereas it is supposed to output `Hello World How Are You`. – Arvind Kumar Avinash Apr 06 '21 at 05:02
1

Shorter version

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

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 !

DevTheJo
  • 2,179
  • 2
  • 21
  • 25