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

如何在JavaScript中使用.match()方法求和字符串中的数字

用正则.match()提取字符串数字并求和的解决方案

你已经通过text.match(/\d+/g)拿到了字符串中的数字字符串数组(比如示例里的["3", "10", "44"]),接下来只需要把这些字符串转成数字,再累加求和即可,下面是两种实现方式:

方法一:用数组reduce方法(简洁写法)

function func() {
  const text = "hi 3 how 10 are you 44"
  const regex = /\d+/g; 
  const matches = text.match(regex); 

  // 处理无匹配数字的情况,避免报错
  if (!matches) return 0;

  // 转数字并累加求和
  const count = matches.reduce((total, numStr) => total + Number(numStr), 0);

  return count === 57 ? 'yes' : count;
}
func(); 

reduce()方法会遍历数组,每次将当前数字字符串转成数字后加到累加器total上,初始值设为0保证空数组时返回0。

方法二:用for循环(直观易懂)

function func() {
  let count = 0;
  const text = "hi 3 how 10 are you 44"
  const regex = /\d+/g; 
  const matches = text.match(regex); 

  // 只有存在匹配项时才遍历累加
  if (matches) {
    for (const numStr of matches) {
      count += Number(numStr);
    }
  }

  return count === 57 ? 'yes' : count;
}
func(); 

通过for...of遍历数字字符串数组,逐个转成数字后累加到count变量中。

注意事项

  • 必须判断matches是否为null:如果目标字符串里没有任何数字,match()会返回null,直接遍历会抛出错误。
  • 用Number()或parseInt(numStr, 10)都可以将字符串转成数字,前者更简洁,后者可以明确指定十进制解析。

内容的提问来源于stack exchange,提问作者Node.jsMaster

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:05:32