var arr=[...];
var html = '<input attr="' + serialize(arr) + '">';
I can't simply join(' ') the arr as there may be white space or other special characters.
How do I do it properly?
You probably want .data, using which you can store any data on a DOM element.
var html = $("<input>");
html.data("something", arr);
Then you can append it somewhere using the insertion methods like .append.
Fetch the data again with:
var arr = html.data("something");
An alternative would be using JSON to convert things into a string and setting that as an attribute:
var html = $("<input>").attr("data-something", JSON.stringify(arr));
And the other way round:
var arr = JSON.parse(html.attr("data-something"));
.data is by far the most convenient way of storing data on an element.'<input attr="' + JSON.stringify(arr) + '" />'? This may break DOM because of ' and "..." around their keys so that would break up with the attribute ".)You may want to look at the .data() method. This allows you to attach arbitrary objects to DOM elements.