Converting an Array to a String in JavaScript

I have an array of strings in JavaScript, and I need to convert it into a single string with specific delimiter characters between the elements. Here’s a sample array:

let myArray = ["apple", "banana", "cherry", "date"];

I want to convert this array into a single string with a comma and space (", ") between each element. The desired output should look like this:

"apple, banana, cherry, date"

Please send me the JavaScript code I need to do this conversion. If I wish to use a different character or characters between the array components, how can I change the delimiter? I looked for a solution by visiting many sources, but I was unsuccessful. Please help me with this, Thank you.

2 Likes

Here’s an example of how I string together the keywords from an JSon array:
Keywords = Data.keywords_and_keyphrases
KeywordString = 'Keywords: ’
for (let i = 0; i < Keywords.length; i++) {
Keyword = Keywords[i]
KeywordString = KeywordString + Keyword + ', ’
}
As you can see they’re separated by a comma + ‘, ’ which could equally be +’: ’

1 Like

In your example you could just do:

myArray.join(“, “);

You can pass any string to the join method as a delimiter. See Array Join method documentation

1 Like

Well, you have to use the join method to do what you are looking for.

let myArray = ["apple", "banana", "cherry", "date"];
let delimiter = ", "; // You can change this to your desired delimiter

let result = myArray.join(delimiter);

console.log(result);

Thanks

1 Like