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

如何用正则表达式拆分JavaScript数组提取操作数与运算符

解决JavaScript数组拆分数字与运算符的问题

原代码的问题

  • indexOf方法不支持正则匹配,用store1.indexOf(re)无法定位运算符位置
  • 多次调用splice会直接修改原数组,第一次执行后原数组已被截断,后续的indexOf自然找不到目标元素,因此只能单独启用一条语句生效

正确实现方案

方案一:遍历数组定位运算符(推荐)

这种方法不修改原数组,逻辑清晰且兼容性强:

const store = ["7", "1", "+", "9", "6"];
// 定义所有支持的运算符集合
const validOperators = new Set(['+', '-', '*', '/']);

// 找到第一个运算符的索引位置
const operatorPos = store.findIndex(item => validOperators.has(item));

if (operatorPos !== -1) {
  // 提取运算符前的数字字符,合并后转为数字
  const number1 = parseInt(store.slice(0, operatorPos).join(''), 10);
  // 提取运算符
  const operator = store[operatorPos];
  // 提取运算符后的数字字符,合并后转为数字
  const number2 = parseInt(store.slice(operatorPos + 1).join(''), 10);

  console.log(number1);  // 输出:71
  console.log(operator); // 输出:+
  console.log(number2);  // 输出:96
} else {
  console.log("数组中未找到有效运算符");
}

方案二:转字符串后用正则匹配

如果可以确定数组格式是「纯数字字符+单个运算符+纯数字字符」,可以用正则简化实现:

const store = ["7", "1", "+", "9", "6"];
const combinedStr = store.join('');
// 匹配数字串+运算符+数字串的固定模式
const matchResult = combinedStr.match(/^(\d+)([+\-*/])(\d+)$/);

if (matchResult) {
  const number1 = parseInt(matchResult[1], 10);
  const operator = matchResult[2];
  const number2 = parseInt(matchResult[3], 10);

  console.log(number1);  // 输出:71
  console.log(operator); // 输出:+
  console.log(number2);  // 输出:96
} else {
  console.log("数组格式不符合要求(需包含且仅包含一个运算符)");
}

为什么多splice语句不能同时生效?

splice是直接修改原数组的方法,第一次执行store1.splice(0, store1.indexOf('+'))后,原数组store1会被截断为['+', '9', '6'],此时再查找'-'、'*'等运算符自然找不到,因此只有单独启用一条语句时才能正常工作。

内容的提问来源于stack exchange,提问作者Jermain Singleton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 03:36:09