You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中统计字符串内各类字符的正则匹配次数?

JavaScript获取正则匹配次数的简便方法

可以直接利用JavaScript内置的String.prototype.match()方法,结合全局正则表达式快速统计各类字符的匹配次数,具体实现如下:

示例代码

const string = "AABBCCaabbcc123!@#";

// 统计大写字母数量(匹配A-Z)
const upperCount = (string.match(/[A-Z]/g) || []).length;
// 统计小写字母数量(匹配a-z)
const lowerCount = (string.match(/[a-z]/g) || []).length;
// 统计数字数量(匹配0-9,等价于/\d/g)
const numberCount = (string.match(/[0-9]/g) || []).length;
// 统计特殊字符数量(匹配非字母、非数字的字符)
const specialCount = (string.match(/[^A-Za-z0-9]/g) || []).length;

// 输出结果
console.log(`大写字母数量:${upperCount}`);   // 6
console.log(`小写字母数量:${lowerCount}`);   // 6
console.log(`数字数量:${numberCount}`);     // 3
console.log(`特殊字符数量:${specialCount}`); // 3

关键说明

  • match(/正则/g):添加g(全局匹配)标志后,方法会返回所有匹配结果组成的数组;如果没有匹配项,会返回null。
  • || []:为避免null调用length报错,用空数组兜底,此时空数组的length为0,符合无匹配时的统计逻辑。

内容的提问来源于stack exchange,提问作者박상욱

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 19:05:03