Concatenate content from a String Array (JSON) generating a sentence

Asked

Viewed 598 times

4

I’m trying to join the contents of an array of strings into one sentence, but I can only bring the whole content separated by commas. Detail, this array comes from a JSON file that is consumed by another JSON file.

The output of my code is:

["John","Peter","Sally","Jane"]

What I need:

John Peter Sally Jane

<!DOCTYPE html>
<html>
<body>

<h2>Create JSON string from a JavaScript array.</h2>

<p id="demo"></p>

<script>

var arr = [ "John", "Peter", "Sally", "Jane" ];
var myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;

</script>

</body>
</html>

In that case, I used the method JSON.stringify, but someone knows another method that will enable me to do what I need?

Note: I don’t use any programming language, it’s a JSON file that consumes data from another, so it’s not possible to simply loop by concatenating the array strings. I used HTML here only to display code output.

  • 4

    Use the method join() to join all elements of an array ... var arr = [ "John", "Peter", "Sally", "Jane" ]; document.getElementById("demo").innerHTML = arr.join(' ');

1 answer

7


I believe you’re looking for the method Array.prototype.join().

The method join joins all elements of an array into a string and returns it.

join accepts a parameter, which will be the separator inserted between strings.

// Aqui ao criar o array já é feito o join resultando em uma string
var jointedStr = [ "John", "Peter", "Sally", "Jane" ].join(' ');
var myJSON = JSON.stringify(jointedStr);

// Troquei innerHTML por innerText porque o alvo é texto e não a estrutura html.
document.getElementById("demo1").innerText = "String: " + jointedStr;
document.getElementById("demo2").innerText = "JSON: " + myJSON;
<!DOCTYPE html>
<html>
<body>

<h2>Create JSON string from a JavaScript array.</h2>

<p id="demo1"></p>
<p id="demo2"></p>



</body>
</html>

  • 1

    It worked for me, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.