Demion
Demion

Reputation: 867

Remove array delimiters

Is it possible remove delimiters when you array.toString? (javascript)

var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
var result = myArray .toString();

result shoud be "zeroonetwothreefourfive"

Upvotes: 6

Views: 7583

Answers (5)

kubetz
kubetz

Reputation: 8556

You can use array.join("separator") instead.

["a", "b", "c"].join("");  // "abc"
["a", "b", "c"].join(" "); // "a b c"
["a", "b", "c"].join(","); // "a,b,c"

Upvotes: 3

ipr101
ipr101

Reputation: 24236

You could use join instead of toString -

var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
var result = myArray.join('');

join will join all the elements of the array into a string using the argument passed to the join function as a delimiter. So calling join and passing in an empty string should do exactly what you require.

Demo - http://jsfiddle.net/jAEVY/

Upvotes: 21

FishBasketGordo
FishBasketGordo

Reputation: 23142

You can you the replace[MDN] method:

var arr = [1,2,3,4],
    arrStr = arr.toString().replace(/,/g, '');

Upvotes: 3

David Laberge
David Laberge

Reputation: 16051

Normally the separator is , to remove the separetor use the function .replace(/,/g,'')

But if there is comma , in the data you might want to consider something like

var str = '';
for(var x=0; x<array.length; x++){
  str += array[x];
}

Upvotes: 1

jabclab
jabclab

Reputation: 15042

You can just use Array.join() to achieve this:

var arr = ["foo", "bar", "baz"],
    str1 = arr.join(""), // "foobarbaz"
    str2 = arr.join(":"); // "foo:bar:baz"

Whatever you specify in the join method will be used as the delimiter.

Upvotes: 6

Related Questions