John
John

Reputation: 13729

JavaScript Join inserts comma delimiter when only one item in array

I'm filtering XHTML classes; when there is only a single class it inserts a comma at the beginning. This makes classes that are hidden to have a value ",hidden" which ends up displaying hidden content. What am I missing? No frameworks please, I never use them.

var d = new Array();

for (var i=0;i<c.length;i++)
{
 if (c[i]==c1) {d.push(c2);}
 else if (c[i]==c2) {d.push(c1);}
 else if (c[i]!='') {d.push(c[i]);}
}

d.join(' ');
alert(d);

Upvotes: 2

Views: 4228

Answers (3)

Dr.Molle
Dr.Molle

Reputation: 117334

d is still an array after using join(). Store the result of join() in a variable to get the resulting string:

joined=d.join(' ');
alert(joined);

Upvotes: 2

alex
alex

Reputation: 490283

You probably have an Array, of which there is an undefined, null or empty string as the first member, which is having its toString() called somewhere (perhaps implicitly), which calls its join() and the default joiner is the comma (,), resulting in a string with a comma at the start.

>>> [null,'hidden'] + '';
",hidden"

Upvotes: 3

Daniel J&#228;ger
Daniel J&#228;ger

Reputation: 187

You could use something like:

if (d.length == 1) {
    alert(d[0].substr(1, d[0].length));
}

to clear the first sign.

Upvotes: 0

Related Questions