計算字串中的標點符號總數 - 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
廣告