在 JavaScript 中計算字串中的特殊字元數量


假設我們有一個字串,其中可能包含以下任一字元。

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

我們需要編寫一個 JavaScript 函式,該函式獲取一個字串,計算字串中這些字元出現的次數並返回該次數。

示例

程式碼如下 −

const str = "This, is a-sentence;.Is this a sentence?";
const countSpecial = 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(countSpecial(str));

輸出

控制檯中的輸出 −

5

更新於: 15-10-2020

1K+ 次瀏覽

啟動您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.