Bill
Bill

Reputation: 5150

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')

Upvotes: 0

Views: 71

Answers (3)

Niklesh Raut
Niklesh Raut

Reputation: 34914

You are not calling function func rather you are just creating a string which looks like function in below line ,

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);

Upvotes: 0

Jamie McElwain
Jamie McElwain

Reputation: 462

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

You need to escape the single quotes using a \

Upvotes: 5

Robby Cornelissen
Robby Cornelissen

Reputation: 97140

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')

Upvotes: 1

Related Questions