Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wrapping a javascript variable with double quotes

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?

like image 505
Imesh Chandrasiri Avatar asked Jul 13 '26 06:07

Imesh Chandrasiri


2 Answers

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)
like image 69
Isaac Avatar answered Jul 15 '26 19:07

Isaac


`${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";
like image 29
Amadan Avatar answered Jul 15 '26 18:07

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!