Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

join array enclosing each value with quotes javascript

How can join an array into a string and at the same time enclosing each value into this

'1/2/12','15/5/12'

for (var i in array) {     dateArray.push(array[i].date); } dateString=dateArray.join(''); console.log(dateString); 
like image 980
anjelott1 Avatar asked Aug 02 '12 01:08

anjelott1


People also ask

How do you enclose data in an array?

In general, when creating an array, you use the new operator, plus the data type of the array elements, plus the number of elements desired enclosed within square brackets ('[' and ']'). As you can see from the example, to reference an array element, you append square brackets to the array name.

How do you add a double quote to an array?

You just need to add quotes. In a string literal delimited with double quotes ( "example" ), you use a backslash in front of a double quote in order to have the quote in the string (instead of having it end the string literal), like this: "here's a quote: \" that was it." .

What does it mean when a word is surrounded with quotes in JavaScript?

Both single (' ') and double (" ") quotes are used to represent a string in Javascript.

How do you escape a double quote in JavaScript?

We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.


1 Answers

If your dates are already strings, you can do the following

var dates = ['1/2/12','15/5/12'];  console.log("'" + dates.join("','") + "'"); 

However, a cooler and more foolproof way (for the case with no dates) way would be Array.prototype.map

// Array.prototype.map returns a new array by  // mapping each element in the existing array dates.map(function(date){     // Wrap each element of the dates array with quotes     return "'" + date + "'"; }).join(","); // Putsa comma in between every element 

Or in es6 lingo

dates.map(date => `'${date}'`).join(','); 

http://jsfiddle.net/yMvVh/

like image 97
Juan Mendes Avatar answered Sep 22 '22 13:09

Juan Mendes