The split method of JavaScript

The split method of JavaScript is used to split or break a given string, generally by a specified separator like space or comma.

The Split method returns an array of broken substrings that you can manipulate just like other arrays in JavaScript.

An example of split method

In this tutorial, we will explain how to use the split method with examples, first look at its syntax.

How to use the string split method?

Following is the general syntax to use the JavaScript string split method:

Str.split(separator, limit);

Where:

Str is a string that you want to split.

The JS Split method has two optional parameters.

  • The Separator is where you specify the character(s) to break the string. If you leave it blank, the split method will return the single string which is the whole given string.
  • The Limit defines the number of pieces, the string will be converted into after split.

A split string example

Following is a split string JavaScript example. In this example, we will use a “space” as a separator without the limit parameter. The alert shows the broken string after using the split method.

Click the image or link below to see it online:

Experience this example online

As you can see in the example the string, “This is a split tutorial!” is used in the split method with space as a separator.

The substrings after split method are shown, which is an array that shows comma separated values after using the split method.

A split example with limit parameter

Following example uses the limit parameter in the split method. In the above example, whole string was broken. As such, the limit parameter specifies numbers of splits, we will use 3 int number and let us look at its output:

Experience this example online

You can see only three substrings are shown in the returned array after using the split method.

A split example with for loop

As such, the string split method returns an array. In the above example, we simply displayed the returned array in an alert, which is shown as comma separated just like ordinary arrays.

In this example, we will use a for loop to iterate through array elements of the returned array after using the split method. The elements of the array will be shown in an HTML paragraph.

Experience this example online

We simply used the space separator in the split method without using the limit parameter. The returned array str_split is then used in the for loop to display array elements in the paragraph.

Similarly, you can use other array methods or properties in returned array after using the split method.

A split example without a separator

As mentioned earlier, if you do not specify any separator then JavaScript split string method will return the whole string, as a single array element. See example below:

Experience this example online

You can see whole string is displayed in an alert.

Related JavaScript String|JavaScript replace string method