Creating arrays by using split method in a string

Array Split We have seen how to create string using elements of an array. Now we will see how to create an array from a string by using some delimiter. For this we will use split() method which works on a string and create array out of it. This is one of the method used to create an array. Here is the basic syntax for using split() method.
var array_name=string_variable.split(" ");
Here one space is used as delimiter for creating an array. Now let us use one string variable to store a sentence and create an array out this by using one space as delimiter in a split() method. Here is the complete code for this.
var str="this is my new tutorial";
var a1 = new Array();
a1=str.split(" ");
document.write(a1.join(" <br> "));
We have used join to generate a string by joining elements through line breaks. Here is the output
this
is
my
new
tutorial

Breaking without any delimiter

If we don't use any landmark for breaking the string then it will be break at each character.
<script type="text/javascript">
var str="Welcome to plus2net";
var a1 = new Array();
a1=str.split("");
/// display elements ///
for (i=0;i<a1.length;i++)
{
document.write(a1[i] + "<br >");
}

</script>
Output is here
W
e
l
c
o
m
e

t
o

p
l
u
s
2
n
e
t

Adding option to limit the array

After using split we are creating an array. We can limit the array creation to limited number of elements by adding optional parameter limit.
Here is the sample code.
<script type="text/javascript">
var str="Welcome to plus2net. You can learn web programming and use them in your applications";
var a1 = new Array();
a1=str.split(" ",3);
/// display elements ///
for (i=0;i<a1.length;i++)
{
document.write(a1[i] + "<br >");
}

</script>
The output is here
Welcome
to
plus2net.

Breaking email address using split

We can break any email address by using @ as delimiter to separate userid ( or name ) and the domain part.
<script type="text/javascript">
var str="username@example.com";
var a1 = new Array();
a1=str.split("@");
document.write (a1[0] + "<br>" + a1[1]);
</script>
Output is here
username
example.com

Demo of creating array from a string by using split

Visitors Rating
Your Rating





max

24-10-2012

Using a for loop (not a for-in loop.) Output 0 to 9 comma delineated no spaces. Output will be 0,1,2,3,4,5,6,7,8,9, in javascript

Post Comment This is for short comments only. Use the forum for more discussions.




HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer