In this post, we will learn how to create a string by joining the elements of an array in JavaScript. So how we can do this, we will learn in this post. 


How To Create A String By Joining The Elements Of An Array In JavaScript ?


Create A String By Joining The Elements Of An Array

To create a string by joining the elements of an array in JavaScript, we use  join()  method. This method returns the array as a string. This method allow us to specify separator to separate the array elements. The default separator is comma( , ). So how we can use this method, we will see it in the example below.


<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How To Create A String By Joining The Elements Of An Array In JavaScript ?</title>
</head>
<body>

<h3>Joining array elements with different separators.</h3>


<!-- Joining array elements without separator. Default separator( , ) -->
<p id="join1"></p>


<!-- Joining array elements with comma( , ) separator. -->
<p id="join2"></p>


<!-- Joining array elements with plus( + ) separator. -->
<p id="join3"></p>


<!-- Joining array elements with dash( - ) separator. -->
<p id="join4"></p>


<!-- Joining array elements without space( "" ) separator. -->
<p id="join5"></p>


<!-- Joining array elements with space( " " ) separator. -->
<p id="join6"></p>



<script>

//Array of elements
var progLang = ["HTML", "CSS", "JavaScript"];


//Joining array elements without separator. Default separator( , )
document.getElementById("join1").innerHTML = progLang.join();


//Joining array elements with comma( , ) separator.
document.getElementById("join2").innerHTML = progLang.join(", ");


//Joining array elements with plus( + ) separator.
document.getElementById("join3").innerHTML = progLang.join(" + ");


//Joining array elements with dash( - ) separator.
document.getElementById("join4").innerHTML = progLang.join("-");


//Joining array elements without space( "" ) separator
document.getElementById("join5").innerHTML = progLang.join("");


//Joining array elements with space( " " ) separator.
document.getElementById("join6").innerHTML = progLang.join(" ");

</script>
</body>
</html> code-box



Summary

In this post we learned how to create a string by joining the elements of an array in JavaScript. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts. 

Post a Comment

Previous Post Next Post