. Advertisement .
..3..
. Advertisement .
..4..
Data structure come in different forms and the array is a very common data structure. Sometimes you need to convert an array into a string so that you can output it to a text file or pass it to another function that expects string values. If you are not sure how to convert array to string Javascript, this article will walk you through the process.
Use Array.toString() function
Array.toString() is a function used to convert an array to a string in Javascript. The return result is a comma-separated string.
Syntax:
const str = Arr.toString();
In which, Arr is the array to be converted to string.
Here is example:
const arr = ["one", "two", "three", "four"];
const str = arr.toString();
console.log(str);
Output:
// output is "one,two,three,four"
Remember to consider that toString
method cannot be applied for any array of objects since it returns[object object]
instead of actual value.
Its use is simply to convert an array to a string and each element is separated by commas, so in practice this function is rarely used in arrays.
Use JSON.stringify function
The JSON.stringify() function helps us convert a Js object to a string for transmission. Objects can’t be passed, and strings are passable because they’re in text format. The Js object or value from your code is passed to the server via Ajax.
For example, we have object in Js and use JSON.stringify() function to convert it to a string:
const users = [
{ name: "John" },
{ name: "Lisa" },
{ name: "Jack" },
{ name: "Mary" },
];
const str = JSON.stringify(users);
console.log(usersToString);
// [{"name":"John"},{"name":"Lisa"},{"name":"Jack"},{"name":"Mary"}]"
Use Array.join to replace the Array.toString function in Javascript
In addition to the toString() function, you can also use the join function to convert an array to a string. The difference is that the toString function you can’t choose the separator character, and the join function can.
For example:
const arr = [1, 2, 3];
arr.join(); // "1,2,3"
arr.join("+"); // "1+2+3"
arr.join(" "); // "1 2 3"
or
[1, 2, 3].join(""); // 123
With that, we have finished the tutorial on how to convert from array to string in Javascript
Conclusion
If you need to convert array to string Javascript, there are several ways to do it. You can use the built-in toString() function or the JavaScript String object. If you want to let the user specify how they want their data formatted, you can use the join method. Take a look at each example carefully to choose the method that’s easy for you. Thanks for reading!
Leave a comment