Thank you for taking the time to address my query. I believe that what I am looking for is not exactly string interpolation, so I have adjusted the title accordingly. Before dismissing this as a duplicate related to string interpolation in JavaScript, please carefully consider the specifics of my question. While I have explored other questions on interpolation in JavaScript, none of them provide the exact solution I am seeking for my code (I explain the reasons in my question), and I prefer not to rely on plugins.
Hello everyone, let me clarify the purpose behind this code. The main objective is to create Query Binding for Express with MySQL, but I intend to utilize this code for other purposes as well.
I am interested in achieving string interpolation in JavaScript/Typescript that functions similarly to Query Binding in Code Igniter - you can find an example here.
// Code 1
let person = 'ujang'
let age = 23
console.log("Hello, %s. You're age is %d years old.", person, age)
// Hello, ujang. You're age is 23 years old.
// A function similar to this code
// $sql = "insert into tbl_user (name, age, groupname) values (?, ?, ?)";
// $this->db->query($sql,array('codeigniter, 35, 'Group 1'));
In the above code snippet, I utilize console.log as it aligns with my requirements, however, since console.log returns void and does not return any value, it cannot be used in practical scenarios.
// Code 2
const str = 'hello, %s. Do you want %d slices of cake?'
const name = 'ujang'
const quantity = 13
const myFunction = (value, ...optionalParams) => {
// The function I need should resemble Query Binding in Code Igniter
// And accommodate dynamic parameters
// This is just a sample
value = value.replace('%s', optionalParams[0])
value = value.replace('%d', optionalParams[1])
return value
}
myFunction(str, name, quantity)
// hello, ujang. Do you want 13 slices of cake?
In Code 2, I attempted to create a function that operates as desired, albeit only for static parameters.
// Code 3
const names = 'ujang'
const arg1 = 'good'
const argN = 'better'
const dontWantFunction = (value, arg1, argN) => {
return `hello, ${value}, this function may be ${arg1} but there could be a ${argN} alternative.`
}
dontWantFunction(names, arg1, argN)
// hello, ujang, this function may be good but there could be a better alternative.
In Code 3, I crafted a function that does not meet my expectations as it is difficult to manage and contains hardcoded text within.
Could anyone assist with refining the myFunction
in Code 2
?
Is anyone else working on a similar codebase?
Alternatively, does anyone know of any documentation or articles that might guide me towards a solution?
Your insight and assistance would greatly benefit me. Thank you for your attention.