var fruits = ['apple', 'peaches', 'oranges', 'mangoes']; var str = fruits.toString(); //print str: apple, peaches, oranges, mangoes
valueOf() that does the same thing.
var fruits = ['apple', 'peaches', 'oranges', 'mangoes']; var str = fruits.valueOf(); //print str: apple,peaches,oranges,mangoes
valueOf() method returns the primitive value of an array. Again the returned string will separate the elements in the array with commas. There is no difference in toString() and valueOf(). Try with different data types like number, strings etc it would give the same result. Also sometimes one wants to create delimited string from an array. Lets say pipe (|) separated string!. In such cases Arrays
join() method comes quite handy. The join() method joins the elements of an array into a string, and returns the string. By default the join() method returns a comma (,) separated value of the array. But you can give argument to join() method and specify the separator. For example:
var fruits = ['apple', 'peaches', 'oranges', 'mangoes']; var str = fruits.join("|"); //print str: apple|peaches|oranges|mangoes
Let us see how to convert a string with commas in it into an Array. Consider following case:
var fruits = ['apple', 'peaches', 'oranges', 'mangoes']; var str = "apple, peaches, oranges, mangoes"; var fruitsArray = str.split(","); //print fruitsArray: apple
Thus split() method of String comes handy for this. It is used to split a string into an array of substrings, and returns the new array. The split() method does not change the original string. Check the sytax of split() method.
separator(Optional). Specifies the character, or the regular expression, to use for splitting the string. If omitted, the entire string will be returned (an array with only one item
limit(Optional). An integer that specifies the number of splits, items after the split limit will not be included in the array
Note: If an empty string (“”) is used as the separator, the string is split between each character. Thus:
var str="How are you doing today?"; var n=str.split("");
The result of n will be an array with the values:
H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?