How do you convert an array of characters to a string in JavaScript?
var s = ['H', 'e', 'l', 'l', 'o'];
// How to convert s to a string?
You do it this way:
var str = s.join();
.join()
will use ","
as a default. But then OP didn't specify how it should be converted, so nothing wrong with your answer.
Commented
Sep 15, 2011 at 3:02
.join()
i.e. without an argument, the string will be "H,e,l,l,o". Yes, as @patrick mentioned, since I didn't specifically stated what output I was looking for (actually, "Hello") this answer is still valid.
The join command lets you set the token among the items in the array.
Ex1:
function print(str) {
$("#result").append("<p>" + str + "</p>");
}
print(["A", "B", "C"].join()); // "A,B,C"
print(["A", "B", "C"].join("-")); // "A-B-C"
print(["A", "B", "C"].join("||")); // "A||B||C"
print(["A", "B", "C"].join("")); // "ABC"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Or use String.
var string = String([1,2,3]);
s.toString()
or any implicit conversion to string - unlikely to be what the OP asked for.
Commented
Sep 15, 2011 at 5:48
1,2,3
, but the OP almost certainly wants 123
.
If you have an array like let array1 = ['a', 'b', 'c']
you can try array1.join('')
the ourput will be 'abc'