我正在尝试使用正则表达式编写 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)'
如果你的代码是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>