How to Use the JavaScript Split Method to Split Strings and String Objects

javascriptsplitProgrammers often wish they had a crystal ball to predict the future. As a programmer you spend hours setting up data or databases to store specific information, only to find out that the information you’ve stored needs to be stored or accessed in a different way. Luckily there are functions within programming languages that allow you as a programmer to manipulate the way data is stored or used as output.

This following tutorial will illustrate how the JavaScript split function can help you to manipulate data and change the way data can be accessed or stored. Although this is a basic tutorial, I would suggest that you have some basic JavaScript knowledge to follow the concepts covered in this tutorial. You can sign up for a free JavaScript for absolute beginner’s course today from udemy to learn the basics of JavaScript programming. This course covers the different data types in JavaScript as well as covering what an array is and how to use them.

The split function splits string objects into numerous objects that are then stored as various elements of an array object. So before I explain how the split function works, I will quickly cover how JavaScript works with strings and also the basics of what arrays are in JavaScript.

JavaScript strings

The string in JavaScript allows you to store information within a string or an object. The information that can be stored includes text, white spaces, digits and other special text characters. Formatting character like tabs, carriage returns and new line characters can also be stored within the string or object. Properties of a string include the length, prototype and constructor properties.

The string object has a number of methods that can be applied to it to allow for manipulation of the string or string object. String methods include the match(), replace(), search() , slice() and split() methods. Methods are essentially programs that manipulate objects in a predefined way.

Strings are generally stored as a variable within JavaScript code. Here are some examples of strings

var string1 = "This is a string";
var string2 = "john2@email.co.za";
var string2 = "john2@email.co.za";
var string3 = "Mr. John Adams";
var string4 = "He is called \"John\"";

JavaScript arrays

The JavaScript array is an object that allows you to store multiple values within a single array object. Arrays can contain more than one variable or value at a time. The size of the array is unlimited and new items can be added to an array or removed from the array. Arrays can contain a number of strings, a number of methods or even a number of arrays. Arrays that contain other arrays are called multidimensional arrays.

Arrays in JavaScript are created as follows:

var myArray1 = Array["John","Jane","Adam"];
var myArray2 = Array[[“John, NY”],[“Sam” ,”LA”],[“Jack”,”Chicago”]];

Elements within the array are separated by commas and each element in the array can be accessed by the element index that refers to that element.  The index always starts at zero. So for example, to access the first element of myArray1, you need to access myArray1[0].

For a course on JavaScript arrays, strings, and other objects, why not sign up for a course in JavaScript for beginners and learn how to use the various objects that make up the JavaScript object oriented programming language. The course will teach you how to store variables and how to access those stored variables using JavaScript.

The split method syntax

In order to use an object’s method, you need to know and understand the method syntax. The split method syntax can be expressed as follows:

string.split( separator, limit)

The separator criterion tells the program how to split the string. It determines on what basis the string will be split. The separator character can be any regular character.

The limit character tells the program how many elements to create when the string is split. Portions of the string that remain after the split will not be included in the resulting array. The Separator criterion and the limit criterion are both optional parameters.

// This will split a string but since no parameters have been specified
// it will create an array with one element that contains the whole string
string.split()
//This will split a string based on any commas found in the string
string.split(“,”)
//This will split a string based on any whitespaces within the string
string.split(“ “)

Let us take a look at how we can use the split method is some real JavaScript code.

How to split a string

There are numerous reasons why you would need to split a string. Perhaps you need to access the username of a user and the username may be stored as the first part of the user email address. Perhaps you need to store the client’s title, name and surname as separate fields within an array so that you can use or manipulate that data.

Here are some examples of how to split various strings. Our first example will show you what happens when a string is split without specifying any criteria.

Take a look at the following code:

<html>
<body>
<script type="text/javascript">
// Create a variable that contains a string
var myString = "Mr. Jack Adams";
// Create a variable to contain the array
var mySplitResult;
// Use the string.split function to split the string
mySplitResult = myString.split();
for(i = 0; i < mySplitResult.length; i++)
  {
    document.write("<br /> Element " + i + " = " + mySplitResult[i]);
  }
</script>
</body>
</html>

The output of the above set of code looks like this:

Element 0 = Mr. John Adams

The reason that there is only one element within our array is because no criteria were specified within the split function itself.

The code uses the “for” loop to loop through the various elements of the array to be able to print each element. For a course on how to use the for loop and other programming loops in JavaScript, why not sign up for JavaScript fundamentals and learn how to use JavaScript to program for the web?

The separator criteria

Let us add a criterion to the split function to split our string. As mentioned, any characters can be used as the split criteria. In our first split example, we will set whitespaces as the criteria by setting whitespaces as the criteria within quotation marks. Take a look at the next example:

<html>
<body>
<script type="text/javascript">
// Create a variable that contains a string
var myString = "Mr. Jack Adams";
// Create a variable to contain the array
var mySplitResult;
// Use the string.split function to split the string
// using the whitespaces as a criteria for splitting the string
mySplitResult = myString.split(" ");
for(i = 0; i < mySplitResult.length; i++)
           {
  document.write("<br /> Element " + i + " of the array is: " + mySplitResult[i]);
           }
</script>
</body>
</html>

The program would split the string each time it found a white space within the string. The output of the above would therefore be:

Element 0 of the array is: Mr.
Element 1 of the array is: Jack
Element 2 of the array is: Adams

If we wanted to split the string using each character within the string then we could use empty quotation marks. This is what the code looks like to split each character within the string

<html>
<body>
<script type="text/javascript">
// Create a variable that contains a string
var myString = "Mr. Jack Adams";
// Create a variable to contain the array
var mySplitResult;
// Use the string.split function to split the string
// using empty quotation marks as a criteria for splitting the string
mySplitResult = myString.split("");
for(i = 0; i < mySplitResult.length; i++)
           {
  document.write("<br /> Element " + i + " of the array is: " +  |
      mySplitResult[i]);
           }
</script>
</body>
</html>

As you can see from the output below, each character within the string has become a separate element within the array. The output of the above would be:

Element 0 of the array is: M
Element 1 of the array is: r
Element 2 of the array is: .
Element 3 of the array is:
Element 4 of the array is: J
Element 5 of the array is: a
Element 6 of the array is: c
Element 7 of the array is: k
Element 8 of the array is:
Element 9 of the array is: A
Element 10 of the array is: d
Element 11 of the array is: a
Element 12 of the array is: m
Element 13 of the array is: s

You could also use a character as the criterion for splitting the string. It is important to note that the split character does not become part of the resulting array. In the code example below we will use the “c” character as the criterion to split the string:

<html>
<body>
<script type="text/javascript">
// Create a variable that contains a string
var myString = "Mr. Jack Adams";
// Create a variable to contain the array
var mySplitResult;
// Use the string.split function to split the string
// using empty quotation marks as a criteria for splitting the string
mySplitResult = myString.split("c");
for(i = 0; i < mySplitResult.length; i++)
           {
  document.write("<br /> Element " + i + " of the array is: " +  |
      mySplitResult[i]);
           }
</script>
</body>
</html>

The output of the above would be:

Element 0 of the array is: Mr. Ja
Element 1 of the array is: k Adams

Note that the “c” does not appear in the resulting elements of the array.

The limit criteria

The second criteria that can be used in the split function can be used to set a limit to the number array elements that are stored when the string is split.

<html>
<body>
<script type="text/javascript">
// Create a variable that contains a string
var myString = "Mr. Jack Adams";
// Create a variable to contain the array
var mySplitResult;
// Use the string.split function to split the string
// using empty quotation marks as a criteria for splitting the string
mySplitResult = myString.split("", 6);
for(i = 0; i < mySplitResult.length; i++)
           {
  document.write("<br /> Element " + i + " of the array is: " +  |
      mySplitResult[i]);
           }
</script>
</body>
</html>

The output of the above split function limited to six array elements can be seen below:

Element 0 of the array is: M
Element 1 of the array is: r
Element 2 of the array is: .
Element 3 of the array is:
Element 4 of the array is: J
Element 5 of the array is: a

As you can see from the above code examples. manipulating strings and splitting strings into various array elements is fairly simple using JavaScript.

As an object oriented language, JavaScript offers programmers the flexibility of working with objects, and yet JavaScript offers programmers the opportunity of working with a dynamic programming language that offers support for both functional and imperative programming styles.

JavaScript also allows for the creation of scripts for use by a large number of applications. JavaScript applications can be used in web pages, they can be embedded in PDF files and they can be used in Google widgets and applications like Google Docs. JavaScript can even be used to create stand alone applications using applications like Adobe Integrated Runtime which programmers use to build desktop applications using JavaScript.

Why you should develop your JavaScript Skills

Mobile app users downloaded an estimated 82 billion apps in 2013 and the number of downloads are expected to increase to over two hundred billion by the year 2017. This increase in demand for mobile apps means that there will be a drastic increase in demand for developers to develop these apps. A career as an app developer could be a career which offers huge opportunities for success in the future.

One of the new ways of building crossplatform mobile apps includes HTML5, CSS and JavaScript. A career as a JavaScript developer can be both financially rewarding and challenging.

To get a head start in programming with HTML, CSS and JavaScript, why not sign up for the HTML5 APIs For JavaScript – A Course For Web Developers course from Udemy?