0

Good day!!! Am trying to pass a string to a function. The string contains a variable which is defined in the function. That is, it is in the function that the value of the variable will be added to the string that is passed in function call. Something like this as an example


function myfunc(arg){
    
    name = "John Malikberry"
    
    alert(arg)
}


let str =`My name is ${name}`

myfunc(str)

I would like the output to be My name is John Malikberry

Thanks!!!

3 Answers3

1

Don't use a template literal, use an ordinary string, and do the replacement in your function.

function myfunc(arg) {
  name = "John Malikberry"
  console.log(arg.replace(/\$\{name\}/g, name))
}

let str = 'My name is ${name}'
myfunc(str)
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You could do something like this maybe:

function myfunc(arg){
    
    name = "John Malikberry"
    
    alert(`${arg}${name}`)
}


let str ='My name is'

myfunc(str)

This could work. Hope it can help.

Wayne Celestin
  • 149
  • 1
  • 6
0

it is in the function that the value of the variable will be added to the string

So it's not just a string. It should take the string and do something with that string (add the name). That's code. The best thing for passing a piece of code around is a function:

function myfunc(template) {
  let str = template({ name: "John Malikberry" });
  alert(str);
}


let template = ({ name }) => `My name is ${name}`;

myfunc(template)
Thomas
  • 11,958
  • 1
  • 14
  • 23