TIMEX
TIMEX

Reputation: 271904

In Javascript, how do I put single quotes around an array I just "joined"?

[3, 4, 5]
['4', '1', 'abc123']


function combine_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!

Upvotes: 7

Views: 9156

Answers (3)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

Simple logic!

function combine_ids(ids) {
  return (ids.length ? "'" + ids.join("','") + "'" : "");
}
console.log(combine_ids([]));
console.log(combine_ids([3]));
console.log(combine_ids([3, 4, 'a']));

Example output:

(an empty string)
'3'
'3','4','a'

Upvotes: 16

OnTheFly
OnTheFly

Reputation: 2101

how do I put single quotes around an array I just “joined”?

Your approach seems to be unnecessarily complex. You better off:

  1. Create intermediate array with all elements converted toString and quoted
  2. 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 combine_ids( array ) {
  var tmp = [];
  for ( var i = 0; i < array.length; i++ ) {
    tmp[i] = "'" + String( array[i] ) + "'";
  }
  return tmp.join(",");
}

Upvotes: 2

JP Richardson
JP Richardson

Reputation: 39395

Like:

 function myjoin(arr) {
   return "'" + arr.join("','") + "'";
 }

Upvotes: 1

Related Questions