計算字串中的標點符號總數 - JavaScript


在英語中,下列字元全部被視為標點符號 −

'!', "," ,"\'" ,";" ,"\"", ".", "-" ,"?"

我們需要編寫一個 JavaScript 函式,傳入一個字串並統計該字串中出現這些標點符號的次數,然後返回該數量。

示例

下面是此函式的程式碼 −

const str = "This, is a-sentence;.Is this a sentence?";
const countPunctuation = str => {
   const punct = "!,\;\.-?";
   let count = 0;
   for(let i = 0; i < str.length; i++){
      if(!punct.includes(str[i])){
         continue;
      };
      count++;
   };
   return count;
};
console.log(countPunctuation(str));

輸出

控制檯中的輸出: −

5

更新時間:15-9-2020

523 次瀏覽

職業生涯的飛躍

完成課程獲得認證

開始
廣告