如何调用字符串中的函数并将执行结果替换原函数名?
实现字符串中函数名的调用与替换
你需要处理包含函数调用(格式为函数名())的字符串,调用对应函数并用返回值替换原函数名部分,原始字符串和期望输出如下:
原始字符串:
my_computer/project_folder/customer=getCustomer()/getCsvFileName()/controller=getControllerName()
期望输出:
my_computer/project_folder/customer=Customer1/userData.csv/controller=myController
下面是直接实现替换的解决方案:
步骤1:定义业务函数
先确保你需要调用的函数已经定义(以下是模拟示例,替换成你的实际业务逻辑即可):
// 实际业务函数,根据需求修改返回值和逻辑 function getCustomer() { return "Customer1"; } function getCsvFileName() { return "userData.csv"; } function getControllerName() { return "myController"; }
步骤2:正则匹配+替换
使用正则表达式全局匹配所有函数名()模式,调用对应函数并完成替换:
const parquetUploadPath = "my_computer/project_folder/customer=getCustomer()/getCsvFileName()/controller=getControllerName()"; const replacedPath = parquetUploadPath.replace(/(\w+)\(\)/g, (matchedStr, funcName) => { // 检查函数是否存在,存在则调用返回结果,否则保留原内容 if (typeof window[funcName] === 'function') { return window[funcName](); } return matchedStr; }); console.log(replacedPath);
代码说明
- 正则
/(\w+)\(\)/g会全局匹配所有以()结尾的函数调用,捕获组(\w+)提取出纯函数名(比如从getCustomer()中提取getCustomer) replace的回调函数接收两个参数:matchedStr是完整的匹配内容(如getCustomer()),funcName是捕获到的函数名- 检查全局作用域中是否存在该函数,存在则执行并返回结果替换原匹配内容;如果函数未定义,就保留原字符串避免出错
非全局函数的适配
如果你的函数不是挂载在全局window,而是在某个对象中(比如模块化的函数集合),只需调整函数查找的位置即可:
// 假设函数都放在funcs对象中 const funcs = { getCustomer, getCsvFileName, getControllerName }; const replacedPath = parquetUploadPath.replace(/(\w+)\(\)/g, (matchedStr, funcName) => { if (typeof funcs[funcName] === 'function') { return funcs[funcName](); } return matchedStr; });
这样就能一步完成所有函数的调用和替换,比先分割提取再处理的方式更简洁高效。
内容的提问来源于stack exchange,提问作者Garry S
相关产品推荐
相关产品推荐

