1. 程式人生 > 程式設計 >利用JavaScript為句子加標題的3種方法示例

利用JavaScript為句子加標題的3種方法示例

前言

本文基於Free Code Camp基本演算法指令碼“標題案例一句”。

在此演算法中,我們要更改文字字串,以便每個單詞的開頭始終都有一個大寫字母。

在本文中,我將解釋三種方法。首先使用FOR迴圈,其次使用map()方法,第三次使用replace()方法。

演算法挑戰

  • 返回提供的字串,每個單詞的首字母大寫。確保單詞的其餘部分為小寫。
  • 出於此練習的目的,你還應該大寫連線詞,例如“ the”和“ of”。

提供的測試用例

  • titleCase(“I'm a little tea pot”)返回一個字串。
  • titleCase(“I'm a little tea pot”)返回“I'm A Little Tea Pot”。
  • titleCase(“sHoRt AnD sToUt”)返回“ Short And Stout”。
  • titleCase(“HERE IS MY HANDLE HERE IS MY SPOUT”)返回“Here Is My Handle Here Is My Spout”。

1.標題大小寫帶有FOR迴圈的句子

對於此解決方案,我們將使用String.prototype.toLowerCase()方法

String.prototype.split()方法,String.prototype.charAt()方法

String.prototype.slice()方法和Array.prototype.join()方法

  • toLowerCase()的方法返回主字串值轉換為小寫
  • split()的方法通過分離串為子分割字串物件到字串陣列。
  • charAt()的方法返回從字串指定的字元。
  • slice()的方法提取的字串的一部分,並返回一個新的字串。
  • join()的方法連線到一個字串陣列的所有元素。

我們將需要在split()方法的括號之間新增一個空格

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

它將輸出一個由單片語成的陣列:

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

如果不在括號中新增空格,則將得到以下輸出:

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

我們將其合併

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

在FOR迴圈中將大寫前的字串索引0字元

str[i].slice(1)

將從索引1提取到字串的末尾。

為了標準化,我們將整個字串設定為小寫。

有註釋:

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","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");

沒有註釋:

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.使用map()方法對案例進行標題案例

對於此解決方案,我們將使用Array.prototype.map()方法。

  • map()的方法建立呼叫此陣列中的每個元件上的提供功能的結果的新的陣列。使用map會依次為陣列中的每個元素呼叫一次提供的回撥函式,並根據結果構造一個新的陣列。

如上例所示,在應用map()方法之前,我們將小寫並分割字串。

代替使用FOR迴圈,我們將把map()方法作為條件與上一個示例的連線相同。

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

有註釋:

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","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","Pot"].join(' ') => "I'm A Little Tea Pot"
}

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

沒有註釋:

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.使用map()和replace()方法對句子進行標題處理

對於此解決方案,我們將繼續使用Array.prototype.map()方法並新增String.prototype.replace()方法。

replace()的方法返回與一些或通過替換替換的圖案的所有比賽的新字串。

在我們的例子中,replace()方法的模式將是一個字串,該字串將被新的替換替換,並將被視為逐字字串。我們還可以使用正則表示式作為模式來解決此演算法。

如將在第一個示例中看到的那樣,在應用map()方法之前,我們將小寫並拆分字串。

有註釋:

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","pot"];
     
 // Step 3. Map over the array
      .map(function(word) {
  return word.replace(word[0],word[0].toUpperCase());
  /* Map process
  1st word: "i'm" => word.replace(word[0],word[0].toUpperCase());
            "i'm".replace("i","I");
            return word => "I'm"
  2nd word: "a" => word.replace(word[0],word[0].toUpperCase());
           "a".replace("a","A");
           return word => "A"
  3rd word: "little" => word.replace(word[0],word[0].toUpperCase());
             "little".replace("l","L");
             return word => "Little"
  4th word: "tea" => word.replace(word[0],word[0].toUpperCase());
            "tea".replace("t","T");
            return word => "Tea"
  5th word: "pot" => word.replace(word[0],word[0].toUpperCase());
            "pot".replace("p","P");
            return word => "Pot"                            
  End of the map() method */
});

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

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

沒有註釋:

function titleCase(str) {
 return str.toLowerCase().split(' ').map(function(word) {
  return word.replace(word[0],word[0].toUpperCase());
 }).join(' ');
}
titleCase("I'm a little tea pot");

總結

到此這篇關於利用JavaScript為句子加標題的文章就介紹到這了,更多相關JavaScript為句子加標題內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!