views:

154

answers:

3

Hi,

normally JavaScript’s toString() method returns the array in a comma seperated value like this

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

And it returns the output like this zero,one,two,three,four,five.

But I have a requirement to represent the result in this format zero_one_two_three_four_five (replacing the comma with _).

I know we can do this using replace method after converting the array to string. Is there a better alternative available?

Cheers

Ramesh Vel

+6  A: 

myArray.join('_') should do what you need.

edeverett
thanks edeverett.. i should read the javascript basics first... :(
Ramesh Vel
No worries, that's what SO is here for. Good thing is the answer didn't take long to write :-)
edeverett
+2  A: 

Use join to join the elements with a specific separator:

myArray.join("_")
Gumbo
A: 

To serve no other purpose than demonstrate it can be done and answer the title (but not the spirit) of the question asked:

<pre>
<script type="text/javascript">
Array.prototype.toStringDefault = Array.prototype.toString;
Array.prototype.toString = function (delim) {
    if ('undefined' === typeof delim) {
        return this.toStringDefault();
    }
    return this.join(delim);
}
var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];
var result1 = myArray.toString('_');
document.writeln(result1);
var result2 = myArray.toString();
document.writeln(result2);
</script>
</pre>

I don't recommend doing this. It makes your code more complicated and dependent on the code necessary to extend the functionality of toString() on Array. Using Array.join() is the correct answer, I just wanted to show that JavaScript can be modified to do what was originally asked.

Grant Wagner