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

如何用JS正则提取字符串开头的首个数字?PHP转JS技术需求

JavaScript提取字符串开头首段数字的实现

对应你PHP里用preg_match( '/^\d*/', $string, $matches )的需求,JavaScript里可以用两种类似的正则实现方式:

方法一:使用RegExp.exec()

function getLeadingDigits(str) {
  const result = /^\d*/.exec(str);
  return result ? result[0] : '';
}

方法二:使用String.match()

function getLeadingDigits(str) {
  const matches = str.match(/^\d*/);
  return matches ? matches[0] : '';
}

测试验证

  • 输入 '180gr.' → 返回 '180'
  • 输入 '140gr. - 200gr.' → 返回 '140'
  • 输入 'unlimited food' → 返回 ''

原理说明:正则表达式/^\d*/会匹配字符串开头(^)的零个或多个数字(\d*),完全对应你PHP中的逻辑——开头有数字就提取连续的数字段,没有则返回空字符串。

内容的提问来源于stack exchange,提问作者Faye D.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 04:45:05