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);
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.
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." .
Both single (' ') and double (" ") quotes are used to represent a string 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.
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/
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