JavaScript turns the first letter of each word in a string to uppercase and the rest to lowercase

Source: Internet
Author: User



Requirements:



Make sure that the first letter of each word in the string is capitalized, and the remainder is lowercase.



Here I have written two methods, or one method, and the other is a variant of the method.



The first type:


 
 
function titleCase(str) {
  var newarr,newarr1=[]; 
  newarr = str . toLowerCase() . split(" ");
  for(var i = 0 ; i < newarr . length ; i++){
    newarr1 . push(newarr[i][0] . toUpperCase()+newarr[i] . substring(1));
  }
  return newarr1.join(‘ ‘);
}

titleCase("I‘m a little tea pot");


The first method I think is better understood.



The second (this is based on the first method of the change):


 
function titleCase(str) {
  var newarr,newarr1; 
  newarr =str.toLowerCase().split(" ");
  for(var i=0;i<newarr.length;i++){
    newarr[i] = newarr[i][0].toUpperCase()+newarr[i].substring(1,newarr[i].length));
  }
 newarr1 = newarr.join(" ");
 return newarr1;
}
titleCase("I‘m a little tea pot");


The second method reduces the conversion object, and the principle is the same.



The results of both methods are:


I ' m A Little Tea Pot





PS: If there are deficiencies or errors please point out, must be corrected in time.






JavaScript turns the first letter of each word in a string to uppercase and the rest to lowercase


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.