Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add different delimiters in javascript toString()..?

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

like image 892
RameshVel Avatar asked Sep 09 '09 10:09

RameshVel


People also ask

How do I use toString in JavaScript?

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.

What is the opposite of toString in JavaScript?

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.

Can we override toString method in JavaScript?

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.

What is array toString in JavaScript?

JavaScript Array toString() The toString() method returns a string with array values separated by commas. The toString() method does not change the original array.


3 Answers

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

like image 107
edeverett Avatar answered Sep 23 '22 11:09

edeverett


Use join to join the elements with a specific separator:

myArray.join("_")
like image 30
Gumbo Avatar answered Sep 21 '22 11:09

Gumbo


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.

like image 37
Grant Wagner Avatar answered Sep 23 '22 11:09

Grant Wagner