Convert char array to a string in JavaScript
This post will discuss how to convert a char array to a string in JavaScript.
There are several ways to convert a char array to a string in JavaScript, depending on our needs and preferences. Here are some of the most common functions:
1. Using Array.join() function
One common way to convert a char array to a string is to use the Array.join() function. It joins the elements of an array into a string, using the specified separator or an empty string by default. If we use an empty string as the delimiter, we will get a string that contains all the elements of the array without any spaces. Here’s an example:
|
1 2 3 4 |
let charArray = ['H', 'e', 'l', 'l', 'o']; let str = charArray.join(''); console.log(str); // 'Hello' |
2. Using Array.reduce() function
The Array.reduce() function applies a function to each element of an array, accumulating the result in a single value. We can use this function to concatenate the elements of an array into a string. Here’s an example:
|
1 2 3 4 5 |
let charArray = ['H', 'e', 'l', 'l', 'o']; let str = charArray.reduce((acc, curr) => acc + curr, ''); console.log(str); // 'Hello' |
3. Using String constructor
A third way to convert a char array to a string is to use the String constructor. This function converts any value to a string, using the default toString() function of the value. We can use this function to convert an array of characters to a string, but it will also add commas between the characters. However, it may not be what we want if we need a string without commas. Here’s an example:
|
1 2 3 4 5 |
let charArray = ['H', 'e', 'l', 'l', 'o']; let str = String(charArray); console.log(str); // 'H,e,l,l,o' |
4. Using String.fromCharCode() function
The String.fromCharCode() function takes one or more character codes as arguments and returns a string that contains the corresponding characters. We can use the apply() function to pass an array of character codes as arguments. Here’s an example:
|
1 2 3 4 5 |
let charArray = [72, 101, 108, 108, 111]; let str = String.fromCharCode.apply(null, charArray); console.log(str); // 'Hello' |
That’s all about converting a char array to a string in JavaScript. We can choose the function that suits our needs best or create our own custom function.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)