[3, 4, 5]
['4', '1', 'abc123']
function bine_ids(ids){
return ids.join(',');
};
No matter what type of list, I want my function to return a string with single quotes around the elements.
The function should return:
'3','4','5'
and
'4','1','abc123'
I want my resulting string to have single quotes in them!
[3, 4, 5]
['4', '1', 'abc123']
function bine_ids(ids){
return ids.join(',');
};
No matter what type of list, I want my function to return a string with single quotes around the elements.
The function should return:
'3','4','5'
and
'4','1','abc123'
I want my resulting string to have single quotes in them!
Share Improve this question asked Dec 6, 2011 at 22:42 TIMEXTIMEX 272k367 gold badges800 silver badges1.1k bronze badges3 Answers
Reset to default 16Simple logic!
function bine_ids(ids) {
return (ids.length ? "'" + ids.join("','") + "'" : "");
}
console.log(bine_ids([]));
console.log(bine_ids([3]));
console.log(bine_ids([3, 4, 'a']));
Example output:
(an empty string) '3' '3','4','a'
how do I put single quotes around an array I just “joined”?
Your approach seems to be unnecessarily plex. You better off:
- Create intermediate array with all elements converted
toString
and quoted join
the intermediate array
[03:22:35.728] [3, 4, 5].map( function (element) { return "'" + String(element) + "'" } ).join(",")
[03:22:35.736] "'3','4','5'"
--
[03:22:58.925] ['4', '1', 'abc123'].map( function (element) { return "'" + String(element) + "'" } ).join(",")
[03:22:58.933] "'4','1','abc123'"
Note: map
method required JS 1.6+, versions below are requiring you to iterate an array "manually":
function bine_ids( array ) {
var tmp = [];
for ( var i = 0; i < array.length; i++ ) {
tmp[i] = "'" + String( array[i] ) + "'";
}
return tmp.join(",");
}
Like:
function myjoin(arr) {
return "'" + arr.join("','") + "'";
}