110

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?
1

5 Answers 5

178

Use join:

string = s.join("");
1
  • 1
    @Digital_Pane: Thank you, this is exactly what I was looking for i.e. the string will be "Hello".
    – moey
    Commented Sep 15, 2011 at 6:54
8

You do it this way:

var str = s.join();
2
  • 5
    Without an argument, .join() will use "," as a default. But then OP didn't specify how it should be converted, so nothing wrong with your answer.
    – user113716
    Commented Sep 15, 2011 at 3:02
  • With .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.
    – moey
    Commented Sep 15, 2011 at 6:51
8

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>

6

Or use String.

var string = String([1,2,3]);
2
  • 2
    That's the same as s.toString() or any implicit conversion to string - unlikely to be what the OP asked for. Commented Sep 15, 2011 at 5:48
  • 1
    That would yield 1,2,3, but the OP almost certainly wants 123.
    – user9315861
    Commented May 10, 2018 at 16:57
0

If you have an array like let array1 = ['a', 'b', 'c'] you can try array1.join('') the ourput will be 'abc'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.