Dave Melia
Dave Melia

Reputation: 317

How to concatenate array with apostrophy and comma in JavaScript

I cannot figure out the best approach to my problem. I wish to concatenate a list of numbers into an array, and affix '', to it.

For example:

'1234','5678','...

I managed to get it to work with commas by doing:

var radio_comma = document.getElementById("optionsRadios1").value;

if (document.getElementById("optionsRadios1").checked) {
        sku_output = txtArray.join(radio_comma);
} 

I can't figure out how to ammend it with 'number',

I did attempt this with

sku_output = radio_singlequote.concat(x, radio_singlequote, radio_comma);

however it will output '123,123,123,123,123'

Upvotes: 0

Views: 123

Answers (1)

KooiInc
KooiInc

Reputation: 122936

sku_output = "'" + txtArray.join("','") + "'" should give the output you search.

You could make an Array extension for it

Array.prototype.toSingleQuotedString = function () {
  return "'" + this.join("','") + "'";
}
//=> sku_output = txtArray.toSingleQuotedString();

Another angle is using Array.map (see MDN)

sku_output = txtArray.map( function (a) { return "'"+a+"'"; } ).join(',');

Upvotes: 2

Related Questions