Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何升级my parsify(),它可以检测嵌入字符串中的函数,并用javascript中的输出替换该函数?_Javascript_Function - Fatal编程技术网

如何升级my parsify(),它可以检测嵌入字符串中的函数,并用javascript中的输出替换该函数?

如何升级my parsify(),它可以检测嵌入字符串中的函数,并用javascript中的输出替换该函数?,javascript,function,Javascript,Function,我有两个函数,即反字符串()和parsify(),其代码如下所示: function antiString(obj) { return Function('"use strict"; return (' + obj + ')')(); }; // This is a function I learned about from MDN Documents function parsify(str) { str = str.replace(/(\r\n|\n|\r)/gm, "

我有两个函数,即反字符串()parsify(),其代码如下所示:

 function antiString(obj) { 
  return Function('"use strict"; return (' + obj + ')')();
 }; // This is a function I learned about from MDN Documents

 function parsify(str) {
   str = str.replace(/(\r\n|\n|\r)/gm, " ");
   var mat = str.match(/@--func(.*)--@/).pop();
   var anti = antiString(mat);
   var str2 = str.replace(/@--func(.*)--@/, anti);
   return str2;
 };
考虑一个非常简单的函数,名为calc()

 function calc(val) {
    return val.toString(); // Just changes the typeof val to string from our input type that will be number.
 }; 
现在用法:

 var str = "Value will be @--func calc(3/2) --@";
 console.log( parsify( str ) ); // Value will be 1.5
所以,你可以问我的问题是什么!!您可能会看到,我在parsify()的源代码中使用了pop()!那是我的问题。根据定义,pop()指的是最后一个,因此每当我想做这样的事情时:

 var str = "I am @--func calc(4+1) --@, who is @--func calc(2-1) --@ added to @--func calc(16/4) --@";
 console.log( parsify( str ) );
 // Expected Output : I am 5, who is 1 added to 4
// Actual Output : Nothing !!!!!!!
因此,我想升级我的So,我想升级我的parsify()函数,这样它就可以生成输出,作为上面示例中的预期输出。有人能告诉我要改变什么来实现这一点吗


提前感谢

您可以使用一个函数替换搜索部分,并使用非贪婪的
量词来获得尽可能短的搜索字符串

顺便说一句,你不需要
位于功能块的末尾。这可能需要使用

功能反串(obj){
返回函数(''use strict';返回('+obj+'))();
}
函数分解(str){
返回str
.替换(/(\r\n |\n |\r)/gm,“”)
.替换(/@--func(.*?)-@/g,(_,mat)=>防串(mat));
}
函数计算(val){
返回值toString();
}
var str=“我是--func calc(4+1)--@,谁是--func calc(2-1)--添加到--func calc(16/4)--@”;
console.log(parsify(str))