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
myArray.join('_') should do what you need.
Use join
to join the elements with a specific separator:
myArray.join("_")
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's answer has utility when an array is multi-dimensional.
take the array [['Mary','Had'],['A','Little'],['lamb', 'and']]
If you use the Array.join('_') method then the result will be something like:
Mary,Had_A,Little_lamb,and
as the join method uses the .toString() method to assemble each element in the main array and this defaults to using the comma separator.
Changing the Array.toString() method would however produce the desired result.