I have an array..
[1,2,3,4]
and I want a string containing all the elements separated by a newline..
1 2 3 4
but when I try [1,2,3,4].join("\n")
I get
1\n2\n3\n4
I feel like there is an obvious answer but I can't find it!
Convert array to string with newlines using join()The join('\r\n') method is used. '\r\n' is passed in as the method's argument that acts as a separator while converting the array to string values. The array elements are divided into newline using '\r\n'.
A New Console Output Line Will Be Added If you wish to add a new line to the JavaScript new line console while printing a few words, the \n sign for the new line can be used.
To add a line break in array values for every occurrence of ~, first split the array. After splitting, add a line break i.e. <br> for each occurrence of ~.
To convert an array to a string with spaces, call the join() method on the array, passing it a string containing a space as a parameter - arr. join(' ') . The join method returns a string with all array elements joined by the provided separator.
Yes, but if you print that string out it will have newlines in it:
irb(main):001:0> a = (1..4).to_a => [1, 2, 3, 4] irb(main):002:0> a.join("\n") => "1\n2\n3\n4" irb(main):003:0> puts a.join("\n") 1 2 3 4
So it does appear to achieve what you desire (?)
A subtle error that can occur here is to use single quotes instead of double. That also has the effect of rendering the newlines as \n. So
puts a.join("\n") # correct
is not the same as
puts a.join('\n') # incorrect
There is an excellent write up on why this is the case here.
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