Learn to use javascript split string method with examples

The split method of Javascript

The split method is used to split or break a given string, generally by a specified separator like a space or comma. The Split method returns an array of broken substrings that you can manipulate just like other arrays in java.

An example of split method

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

Syntax to use string split

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

Str.split(separator, limit);

Where:

Str is a string that you want to split.

JS Split method has two option parameters.

Separator is where you specify the character(s) to split the string. If you leave it blank the split method will return single string which is whole given string.

Limit defines the number of splits.

A split string example

Following is a split string javascript example. In this example we will use a space as separator without limit parameter. The alert shows broken string after using split method. See example by clicking the link below:

Experience this example online


As you can see in example the string “This is split tutorial!” is used in split method with space as seperator. The substrings after split method are shown, which is an array that shows comma separated values after using split JS method.

Javascript split example with limit parameter

Following example uses limit parameter in split method. In above example whole string was broken. As such limit parameter species 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 retuned array after using split javascript method.

A split example with for loop

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

In this example we will use for loop to iterate through array elements of returned array after using split method. The elements of array will be shown in an HTML paragraph. See example by clicking the link below:

Experience this example online


You can see we simply used space separator in split method without limit parameter. The returned array str_split is then used in for loop to display array elements in paragraph.

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

A split example without separator

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

Experience this example online


You can see whole string is displayed.

Also see: Javascript String | Javascript substring | Javascript replace

Was this article helpful?

Related Articles

Leave A Comment?