js 提取表达式中的变量名和运算符

189 阅读1分钟

直接进入正题,给定一个含有变量的表达式 str = a+b-abs(c*d),通过js解析,得到变量名数组 ['a', 'b', 'c', 'd'] 以及运算符 ['+', '-', 'abs', '*'],方便后续的函数式操作。

经过多方查找mathjs中的parse方法符合我们的要求。

控制台打印 math.parse(str),可以看到:

image.png

官方对math.parse的解释:

当通过math.parse(expr)解析一个表达式时,math.js会生成一个表达式树并返回树的根节点。表达式树可用于分析、操作和计算表达式。

因此我们可以很方便的得到我们想要的变量名,代码如下:

const node = math.parse(val)
const names = node
    .filter((node) => node.type === "SymbolNode")
    .map((node) => (node as math.SymbolNode).name)
const fnName = node
    .filter((node) => node.type === "FunctionNode")
    .map((node) => (node as math.SymbolNode).name)
const colName = names.filter((node) => !fnName.includes(node))

运算符的获取同理。