在 JavaScript 中查找字符串中特殊字符的数量

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/26 7:40:17

假设我们有一个字符串,其中可能包含以下任何字符。

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

我们需要编写一个 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

相关文章


有用资源