Home > Software design >  How do i pass a string which contains a variable to be added to it in function
How do i pass a string which contains a variable to be added to it in function

Time:08-22

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!!!

CodePudding user response:

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)

CodePudding user response:

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.

  • Related