Mona Coder Mona Coder - 2 months ago 8
Javascript Question

How to Wrap Group of Strings in Single Quotes

I need to export elements of an array to strings but keep the single quotes around the elements. As you can see, exporting them to the

toString()
method outputs
Banana, Orange, Apple, Mango
but I need to have them like
'Banana', 'Orange', 'Apple', 'Mango'
.



var fruits = ["Banana", "Orange", "Apple", "Mango"];
var map = fruits.toString();

console.log(map);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>





Can you please let me know how to do this?

Answer

ES6

var fruits = ["Banana", "Orange", "Apple", "Mango"];
// creates a new array containing: ["'Banana'", "'Orange'", "'Apple'", "'Mango'"]
var exportedFruits = fruits.map(fruit => "'" + fruit + "'");
console.log(exportedFruits.toString())

ES5

var fruits = ["Banana", "Orange", "Apple", "Mango"];
// creates a new array containing: ["'Banana'", "'Orange'", "'Apple'", "'Mango'"]
var exportedFruits = fruits.map(function(fruit){
  return "'" + fruit + "'";
});
console.log(exportedFruits.toString())