Lets say I have
const colors = ['red', 'yellow', 'pink']
How can I convert this array to a string:
""red", "yellow","pink""
I have tried: colors.map(id => "'" id "'").join(', ')
but this gives: "'red', 'yellow', 'pink'"
edit: I get answers with variations of what I've tried. Please note I need double quotes outside the string and between each word.
CodePudding user response:
You can try this.
const colors = ['red', 'yellow', 'pink'];
let result = colors.map(c => `"${c}"`).join(',');
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can put double quotes wrapped by single quotes, or escape the double quote inside of double quotes, or use ES6 template literals (introduced in 2015):
const colors = ['red', 'yellow', 'pink']
console.log(colors.map((str) => '"' str '"').join(", "));
console.log(colors.map((str) => "\"" str "\"").join(", "));
console.log(colors.map((str) => `"${str}"`).join(", "));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can use join and replace to achieve the desired result
const colors = ["red", "yellow", "pink"];
let result = colors.join(", ").replace(/[a-z] /gi, `"$&"`);
console.log(result);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>