I've the following code with a string inside a js template literal.
`${currentType} ${objProp} = ${value};`
I want to wrap the ${value} with double quotes when it prints. How can I achieve this?
let currentType = "hello";
let objProp = "world";
let value = "hi";
let a = `${currentType} ${objProp} = "${value}";`
console.log(a)
Just use the double quote surrounding your ${value}
UPDATES:
Just to try out to prove that it can supports double quoted string as below
let value = '"hi"';
let a = `${value}`;
console.log(a)
let value2 = "\"hi\"";
let a2 = `${value2}`;
console.log(a2)
`${currentType} ${objProp} = ${JSON.stringify(value)};`
Using JSON.stringify will do the right thing for all JS primitives, quoting strings, and correctly formatting objects and arrays.
EDIT because so many of other answerers seem to be missing the point:
let currentType = 'string';
let objProp = 'actor';
let value = 'Dwayne "The Rock" Johnson';
let bad = `${currentType} ${objProp} = "${value}";`
console.log(bad);
// string actor = "Dwayne "The Rock" Johnson";
let good = `${currentType} ${objProp} = ${JSON.stringify(value)};`
console.log(good);
// string actor = "Dwayne \"The Rock\" Johnson";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With