The join() method joins all elements of an array into a string, and returns the string.
The elements will be separated by a specified separator. The default separator is comma (,).
Syntax:
array.join(separator)
Optional. The separator to be used. If omitted, the elements are separated with a comma
Join() method is a built in method in JavaScript which takes a delimiter and create a string by adding all elements of the array by placing the delimiter between them.
This is another way to display all elements and if we give line break <br> as delimiter then all elements we can display vertically in any web page. We need not loop through by using length property.
We can directly display elements by using document.write or we can assign it to one string variable and then display.
var str=scripts.join(" : ");
document.write(str);
Here is the complete code for displaying elements of an array using join
<script type="text/javascript">
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
var str=scripts.join(" : ");
document.write(str);
//document.write(scripts.join(" <br> "));
</script>
The output of the above code is here
PHP : ASP : JavaScript : HTML
You can use line break <br> to generate a list by using the last line of the above code.
he ability to split up a string into separate chunks has been supported in many programming languages, and it is available in JavaScript as well. If you have a long string like "Bobby Susan Tracy Jack Phil Yannis" and want to store each name separately, you can specify the space character " " and have the split function create a new chunk every time it sees a space.
<script type="text/javascript">
var myString = "123456789";
var mySplitResult = myString.split("5");
document.write("The first element is " + mySplitResult[0]);
document.write("<br /> The second element is " + mySplitResult[1]);
</script>
Comments