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
The toString() method returns a string as a string. The toString() method does not change the original string. The toString() method can be used to convert a string object into a string.
toString() method when called on a number is the opposite of parseInt, meaning it converts the decimal to any number system between 2 and 36.
The toString() method is automatically invoked when the string value of the object is expected. The method is inherited by the descendants of the object. The objects override the method to return a specific string value. In case the toString() method is not overridden, [object type] is returned.
JavaScript Array toString() The toString() method returns a string with array values separated by commas. The toString() method does not change the original array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With