简体   繁体   English

带单引号参数的Javascript字符串

[英]Javascript string with arguments to single quotes

Call function below relies in double and single quotes how can one convert this to single quotes only and get the same result? 下面的调用函数依赖于双引号和单引号,如何将其仅转换为单引号并得到相同的结果?

const task.func = 'A'
const task.arg = 'B'
const callFunction = "doTask."+task.func+"('"+task.arg+"')"

console.log(callFunction); // doTask.A('B')
const callFunction = 'doTask.' + task.func + '(\'' + task.arg + '\')'

您需要使用\\来转义单引号\\

Escape the single quotes: 转义单引号:

 const task = { func: 'A', arg: 'B' }; const callFunction = 'doTask.' + task.func + '(\\'' + task.arg + '\\')'; console.log(callFunction); // doTask.A('B') 

Or, if you consider a backtick to be a single quote, you can use template literals : 或者,如果您认为反引号是单引号,则可以使用模板文字

 const task = { func: 'A', arg: 'B' }; const callFunction = `doTask.${task.func}('${task.arg}')`; console.log(callFunction); // doTask.A('B') 

You are not calling function func rather you are just creating a string which looks like function in below line , 您不是在调用函数func而是在创建一个字符串,该字符串看起来像下面一行中的function,

const callFunction = "doTask."+task.func+"('"+task.arg+"')";

Also you need not to use quotes, just provide variable name as argument. 另外,您无需使用引号,只需提供变量名称作为参数即可。

Try like this. 尝试这样。

 task = {}; task.func = function (arg){ return 'func called with arg : '+arg; }; task.arg = 'B'; const callFunction = 'doTask.'+task.func(task.arg); console.log(callFunction); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM