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

JavaScript如何从含不同格式PROF/Profit标识的字符串中提取数值

解决方案

你可以通过正则表达式实现需求,忽略大小写匹配Prof开头的字符串,直接捕获其前后的数值即可,可运行代码如下:

// 你的原始字符串数组
var arrStr = [ 
'Slab3 - Slab 1.00 NAV & Slab14- Slab 20.00 PROF 10', 
'Slab3 - Slab 1.00 NAV & Slab14- Slab 20.00PROF 10' , 
'Slab3 - Slab 1.00 NAV & Slab14- Slab 20.00Profit 10', 
'Slab3 - Slab 1.00 NAV & Slab14- Slab 10.00 PROF 12', 
'Slab3 - Slab 1.00 NAV & Slab14- Slab 18.00PROF 12', 
'Slab3 - Slab 1.00 NAV & Slab14- Slab 20.00Profit 12', 
'Slab3 - Slab 1.00 NAV & Slab14- Slab 20.00 Profit 12'
]

// 匹配正则
const profReg = /(\d+\.\d+)\s*prof.*?\s*(\d+)/i;

// 遍历提取结果
const extractResult = arrStr.map(str => {
  const matchRes = str.match(profReg);
  return matchRes ? {
    prof前数值: matchRes[1],
    prof后数值: matchRes[2]
  } : null;
})

// 输出结果
console.log(extractResult);

运行输出

[
  { prof前数值: '20.00', prof后数值: '10' },
  { prof前数值: '20.00', prof后数值: '10' },
  { prof前数值: '20.00', prof后数值: '10' },
  { prof前数值: '10.00', prof后数值: '12' },
  { prof前数值: '18.00', prof后数值: '12' },
  { prof前数值: '20.00', prof后数值: '12' },
  { prof前数值: '20.00', prof后数值: '12' }
]

正则说明

  • (\d+\.\d+):捕获带小数点的浮点数值,对应Prof前面的金额
  • \s*:匹配0个或多个空白字符,兼容数值和Prof之间有没有空格的场景
  • prof.*?:配合末尾的i标志忽略大小写,匹配PROF/Profit/prof等所有以Prof开头的内容,非贪婪匹配避免捕获多余内容
  • \s*(\d+):匹配Prof后的0个或多个空白字符,再捕获后续的整数数值

内容的提问来源于stack exchange,提问作者Hari Krishnan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:09:04