Creating arrays by using split method of a string by using delimiter

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
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 delimiter and split().

Syntax
var array_name=string_variable.split(" ");

Creating arrays in JavaScript & adding elements by using constructor and breaking string using 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
Array Reference How to display elements of an Array
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    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 your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer