Convert a Sentence to InitCap / camel Case / Proper Case

Tushar Gupta - curioustushar picture Tushar Gupta - curioustushar · Nov 8, 2013 · Viewed 14.6k times · Source

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

Answer

anubhava picture anubhava · Nov 8, 2013

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