Implode an array with JavaScript?

ID : 10384

viewed : 21

Tags : javascriptimplodejavascript

Top 5 Answer for Implode an array with JavaScript?

vote vote

90

You can do this in plain JavaScript, use Array.prototype.join:

arrayName.join(delimiter); 
vote vote

81

Like This:

[1,2,3,4].join('; ') 
vote vote

70

Array.join is what you need, but if you like, the friendly people at phpjs.org have created implode for you.

Then some slightly off topic ranting. As @jon_darkstar alreadt pointed out, jQuery is JavaScript and not vice versa. You don't need to know JavaScript to be able to understand how to use jQuery, but it certainly doesn't hurt and once you begin to appreciate reusability or start looking at the bigger picture you absolutely need to learn it.

vote vote

68

For future reference, if you want to mimic the behaviour of PHP's implode() when no delimiter is specified (literally just join the pieces together), you need to pass an empty string into Javascript's join() otherwise it defaults to using commas as delimiters:

var bits = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']; alert(bits.join());    // H,e,l,l,o, ,W,o,r,l,d alert(bits.join(''));  // Hello World 
vote vote

50

Use join() method creates and returns a new string by concatenating all of the elements in an array.

Working example

var arr= ['A','b','C','d',1,'2',3,'4'];  var res= arr.join('; ')  console.log(res);

Top 3 video Explaining Implode an array with JavaScript?

Related QUESTION?