Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to captalize the first character of every word of a string in javascript? [duplicate]

Tags:

javascript

I've looked all over for how to capitalize the first character of every word of a string, but nothing helped me. I need to set an entered string to a heading capital character lower case one . I've tried this:

function titleCase(str) {
//converting the giving string into array
  str =str.split(" "); 
//iterating over all elem.s in the array
  for(var i=0;i<str.length;i++){        
//converting each elem. into string
    str[i]=str[i].toString(); 
//converting the first char to upper case &concatenating to the rest chars
    str[i]=str[i].toUpperCase(str[i].charAt(0))+ str[i].substring(1);
  }
  return str;
}
titleCase("I'm a little tea pot");
like image 469
Mamdouh Elnahla Avatar asked Dec 11 '15 06:12

Mamdouh Elnahla


4 Answers

function firstToUpperCase( str ) {
    return str.substr(0, 1).toUpperCase() + str.substr(1);
}

var str = 'hello, I\'m a string';
var uc_str = firstToUpperCase( str );

console.log( uc_str ); //Hello, I'm a string
like image 200
Mandeep Singh Avatar answered Nov 15 '22 20:11

Mandeep Singh


    function capitalise(string) {
        return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
    }
   capitalise("smallletters") ;// Smallletters
like image 23
Jijesh Cherrai Avatar answered Nov 15 '22 20:11

Jijesh Cherrai


You could simply do:

function capitalFirst(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}
like image 24
GMaiolo Avatar answered Nov 15 '22 22:11

GMaiolo


Try something like this:

String.prototype.titleCase = function(){
    return this[0].toUpperCase() + this.slice(1)
}

Usage:

"hello my name is Jacques".titleCase();

If you want to capitalize the character at the beginning of each word, try something like this:

String.prototype.capitalize = function(){
    return this.split(" ")
               .map(function(){
                   return this[0].toUpperCase() + this.slice(1);
               }).join(" ");
}
like image 45
Jacques Marais Avatar answered Nov 15 '22 20:11

Jacques Marais