只要“x”位于 Math.sin()、Math.cos() 或 Math.tan() 中,如何替换字符串中“x”的所有实例?

问题描述 投票:0回答:1

我正在尝试使用正则表达式编写 JavaScript

replaceAll()
,它将用
x
替换
period*x
的每个值,只要它在
Math.sin()
Math.cos()
Math.tan()

我试过这个:

let fx = 'Math.tan(Math.sin(Math.cos(x)*x)*x)';
const periodRegEx = /(Math.(sin|cos|tan)\(.*?)(x)([^\)].*?)(\))/gi;
// capture group with 'Math.sin(' or 'Math.cos(' or 'Math.tan('
// capture group with 'x'
// capture group with any character except for ')'
// capture group with ')'
let newFx = fx.replaceAll(periodRegEx,('period*'+\2));

但这给我带来了“非法转义序列错误”。这个:

let newFx = fx.replaceAll(periodRegEx,('period*'+'\2'));

什么也没给我,而这个:

let newFx = fx.replaceAll(periodRegEx,('period*'+$2));

给我一个

$2 not defined
错误。

我正在寻找的是

replaceAll()
:

的输出
'Math.tan(Math.sin(Math.cos(period*x)*period*x)*period*x)'
javascript regex capture-group
1个回答
0
投票

如果你的代码是JS(似乎),你可以解析它并用acorn替换它并用astring生成回JS代码:

let fx = 'Math.tan(Math.sin(Math.cos(x)*x)*x)';

const parsed = acorn.Parser.parse(fx, {ecmaVersion: 'es6'});

const replace = node => {
  if(node.name === 'x'){
    node.name = 'period * x';
    return;
  }
  if(Array.isArray(node)){
    node.forEach(replace);
  } else if(typeof node === 'object' && node){
    for(const k in node){
      replace(node[k]);
    }
  }
}
replace(parsed);

const code = astring.generate(parsed);

console.log(code)
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/8.11.3/acorn.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/astring.min.js"></script>

© www.soinside.com 2019 - 2024. All rights reserved.