Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Sentence to InitCap / camel Case / Proper Case

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

like image 622
Tushar Gupta - curioustushar Avatar asked Nov 08 '13 16:11

Tushar Gupta - curioustushar


2 Answers

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());
like image 61
anubhava Avatar answered Oct 14 '22 04:10

anubhava


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.

like image 41
RJLyders Avatar answered Oct 14 '22 04:10

RJLyders