Solution Ideas
- Convert a string to lowercase
- To split a string into a string array
- Loop array capitalize each word first letter
- Converts all elements of an array into a string
The first of these methods
function Titlecase (str) {
Str=str.tolowercase (). Split ('); //Convert string uniformly lowercase, all words are lowercase
var change; //Declare a variable to hold any element of STR
for (Var i=0;i<str.length;i++) {//sequentially loop elements in Str
Change=str[i].split ("); //I+1 the string of str elements into a string array, which divides the word into a word-length array
Change[0]=change[0].touppercase (); //Capitalize the string of the first element in the string array and capitalize the initial letter
Change=change.join ("); //Combine word length array groups with words
Str[i]=change; //Replace the original word with the first capitalized word
}
Str=str.join (");//Combine str array into string
return str; //output array
}
Titlecase ("I ' m a Little tea pot");
The second method of
function Titlecase (str) {
Str=str.split ("); //Splitting a string into a string array
var change; //Declare a variable to hold any element of STR
for (Var i=0;i<str.length;i++) {//sequentially loop elements in Str
Change=str[i].tolowercase (); //Convert the i+1 element in str to lowercase and assign a value to change
Change=change.split ("); //Convert a string into a string array, and a word into an array of word lengths
Change[0]=change[0].touppercase (); //Capitalize the string of the first element in the string array and capitalize the initial letter
Change=change.join ("); //Combine word length array groups with words
Str[i]=change; //Replace the original word with the first capitalized word
}
Str=str.join ("); //Combine str array into string
return str; //output array
}
Titlecase ("I ' m a Little tea pot");
Error Example //Based on the second method of error
function Titlecase (str) {
Str=str.split (");
var change;
for (Var i=0;i<str.length;i++) {
Change=str[i].tolowercase (); //Convert the i+1 element in str to lowercase and assign a value to change
Change=str[i].split ("); //Here the i+1 element in Str that is not converted to lowercase is split into a string array, and the change is assigned again, causing an error
Change[0]=change[0].touppercase ();
Change=change.join (");
Str[i]=change;
}
Str=str.join (");
return str;
}
Titlecase ("I ' m a Little tea pot");
Title case a sentence