JavaScript join, toString example to convert array to string

Published by admin on

JavaScript convert array to string

Javascript array elements to string conversion :

JavaScript provides two methods join() and toString() to convert array elements to a string with comma-separated values. toString() method is inherited from the Object class. It was introduced in ECMAScript 5. Both methods actually return the same string value. One more thing is that we can change the separator in the join method. Let me show you with examples :

 

toString() :

var weeks = ['mon', 'tues', 'wed', 'thurs', 'fri', 'sat', 'sun'];

console.log(weeks.toString());

It will print :

mon,tues,wed,thurs,fri,sat,sun

 

join() :

The join method is defined as below :

join([separator])

It takes one optional separator argument. This method returns one string value same as the toString method. By default, it uses one comma to separate the values. If we provide the separator argument, it will use that separator.

var weeks = ['mon', 'tues', 'wed', 'thurs', 'fri', 'sat', 'sun'];

console.log(weeks.join());

 

Output :

mon,tues,wed,thurs,fri,sat,sun

Using a different separator :

var weeks = ['mon', 'tues', 'wed', 'thurs', 'fri', 'sat', 'sun'];

console.log(weeks.join('-'));

 

Output :

mon-tues-wed-thurs-fri-sat-sun

You can also get the string without any separator :

var weeks = ['mon', 'tues', 'wed', 'thurs', 'fri', 'sat', 'sun'];

console.log(weeks.join(''));

Output :

montueswedthursfrisatsun

JavaScript join toString

Categories: javascript

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *