Examples of three methods of adding titles to sentences by using JavaScript

  • 2021-10-16 01:01:59
  • OfStack

Preface

This article is based on Free Code Camp basic algorithm script "Title Case 1 Sentence".

In this algorithm, we change the text string so that each word always begins with a capital letter.

In this article, I will explain three methods. The FOR loop is first used, the map () method is second, and the replace () method is third.

Algorithm challenge

Returns the supplied string, with the first letter of each word capitalized. Make sure the rest of the word is lowercase. For the purpose of this exercise, you should also capitalize conjunctions such as "the" and "of".

Test cases provided

titleCase ("I 'm a little tea pot") returns a string. titleCase ("I 'm a little tea pot") returns "I' m A Little Tea Pot". titleCase ("sHoRt AnD sToUt") returns "Short And Stout". titleCase ("HERE IS MY HANDLE HERE IS MY SPOUT") returns "Here Is My Handle Here Is My Spout".

1. Sentences with FOR loop in caption case

For this solution, we will use the String. prototype. toLowerCase () method

String. prototype. split () method, String. prototype. charAt () method

String. prototype. slice () Method and Array. prototype. join () Method

The method of toLowerCase () returns the main string value converted to lowercase The method of split () splits string objects into string arrays by separating strings as children. The method of charAt () returns the character specified from the string. The slice () method extracts 1 part of the string and returns 1 new string. The method of join () connects to all the elements of a string array.

We will need to add 1 space between the parentheses of the split () method


var strSplit = "I'm a little tea pot".split(' ');

It will output an array of words:


var strSplit = ["I'm", "a", "little", "tea", "pot"];

If you don't add spaces in parentheses, you will get the following output:


var strSplit = ["I", "'", "m", " ", "a", " ", "l", "i", "t", "t", "l", "e", " ", "t", "e", "a", " ", "p", "o", "t"];

We combine them


str[i].charAt(0).toUpperCase()

Index the string before uppercase to 0 characters in the FOR loop

And


str[i].slice(1)

Will be extracted from Index 1 to the end of the string.

For standardization, we set the whole string to lowercase.

There are notes:


function titleCase(str) {
 // Step 1. Lowercase the string
 str = str.toLowerCase();
 // str = "I'm a little tea pot".toLowerCase();
 // str = "i'm a little tea pot";
 
 // Step 2. Split the string into an array of strings
 str = str.split(' ');
 // str = "i'm a little tea pot".split(' ');
 // str = ["i'm", "a", "little", "tea", "pot"];
 
 // Step 3. Create the FOR loop
 for (var i = 0; i < str.length; i++) {
  str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1); 
 /* Here str.length = 5
  1st iteration: str[0] = str[0].charAt(0).toUpperCase() + str[0].slice(1);
          str[0] = "i'm".charAt(0).toUpperCase() + "i'm".slice(1);
          str[0] = "I"              + "'m";
          str[0] = "I'm";
  2nd iteration: str[1] = str[1].charAt(0).toUpperCase() + str[1].slice(1);
          str[1] = "a".charAt(0).toUpperCase()  + "a".slice(1);
          str[1] = "A"              + "";
          str[1] = "A";
  3rd iteration: str[2] = str[2].charAt(0).toUpperCase()  + str[2].slice(1);
          str[2] = "little".charAt(0).toUpperCase() + "little".slice(1);
          str[2] = "L"               + "ittle";
          str[2] = "Little";
  4th iteration: str[3] = str[3].charAt(0).toUpperCase() + str[3].slice(1);
          str[3] = "tea".charAt(0).toUpperCase() + "tea".slice(1);
          str[3] = "T"              + "ea";
          str[3] = "Tea";
  5th iteration: str[4] = str[4].charAt(0).toUpperCase() + str[4].slice(1);
          str[4] = "pot".charAt(0).toUpperCase() + "pot".slice(1);
          str[4] = "P"              + "ot";
          str[4] = "Pot";                             
  End of the FOR Loop*/
 }
 
 // Step 4. Return the output
 return str.join(' '); // ["I'm", "A", "Little", "Tea", "Pot"].join(' ') => "I'm A Little Tea Pot"
}

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

No comment:


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

2. Header the case using the map () method

For this solution, we will use the Array. prototype. map () method.

The method of map () creates a new array of results that invoke the functionality provided on each element in this array. Using map calls the supplied callback function once in turn for each element in the array and constructs a new array based on the result.

As shown in the above example, before applying the map () method, we will lowercase and split the string.

Instead of using the FOR loop, we'll use the map () method as a condition similar to the join in the previous example.


(word.charAt(0).toUpperCase() + word.slice(1));

There are notes:


function titleCase(str) {
 // Step 1. Lowercase the string
 str = str.toLowerCase() // str = "i'm a little tea pot";
 
 // Step 2. Split the string into an array of strings
      .split(' ') // str = ["i'm", "a", "little", "tea", "pot"];
     
 // Step 3. Map over the array
      .map(function(word) {
  return (word.charAt(0).toUpperCase() + word.slice(1));
  /* Map process
  1st word: "i'm"  => (word.charAt(0).toUpperCase() + word.slice(1));
             "i'm".charAt(0).toUpperCase() + "i'm".slice(1);
                "I"           +   "'m";
             return "I'm";
  2nd word: "a"   => (word.charAt(0).toUpperCase() + word.slice(1));
             "a".charAt(0).toUpperCase()  + "".slice(1);
                "A"           +   "";
             return "A";
  3rd word: "little" => (word.charAt(0).toUpperCase()  + word.slice(1));
             "little".charAt(0).toUpperCase() + "little".slice(1);
                "L"            +   "ittle";
             return "Little";
  4th word: "tea"  => (word.charAt(0).toUpperCase() + word.slice(1));
             "tea".charAt(0).toUpperCase() + "tea".slice(1);
                "T"           +   "ea";
             return "Tea";
  5th word: "pot"  => (word.charAt(0).toUpperCase() + word.slice(1));
             "pot".charAt(0).toUpperCase() + "pot".slice(1);
                "P"           +   "ot";
             return "Pot";                            
  End of the map() method */
});

 // Step 4. Return the output
 return str.join(' '); // ["I'm", "A", "Little", "Tea", "Pot"].join(' ') => "I'm A Little Tea Pot"
}

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

No comment:


function titleCase(str) {
 return str.toLowerCase().split(' ').map(function(word) {
  return (word.charAt(0).toUpperCase() + word.slice(1));
 }).join(' ');
}
titleCase("I'm a little tea pot");

3. Use map () and replace () methods for sentence header processing

For this solution, we will continue to use the Array. prototype. map () method and add the String. prototype. replace () method.

The method of replace () returns a new string for all matches with 1 or a pattern replaced by substitution.

In our example, the pattern of the replace () method will be a string, which will be replaced by the new substitution and will be treated as a verbatim string. We can also use regular expressions as patterns to solve this algorithm.

As we will see in the first example, before applying the map () method, we will lowercase and split the string.

There are notes:


var strSplit = ["I'm", "a", "little", "tea", "pot"];
0

No comment:


var strSplit = ["I'm", "a", "little", "tea", "pot"];
1

Summarize


Related articles: