计算字符串中的标点符号总数 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/5 3:56:17
在英语中,所有这些字符都被视为标点符号 −
'!'、"," 、"\'" 、";" 、"\""、"."、"-" 、"?"
我们需要编写一个 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

