JavaScript String split() Method



The JavaScript String split() method is used to divide a string into an ordered list of substrings based on a specific pattern. This method puts the substrings into an array and returns this array. You can also specify the number of substrings to be included in the array using an optional parameter called "limit".

For example, "Hello World".split(" ", 1) would return "Hello", while "Hello World".split(" ", 2) would return "Hello,World".

Syntax

Following is the syntax of JavaScript String split() method −

split(separator, limit)

Parameters

This method accepts two parameters named 'separator' and 'limit', which are described below −

  • separator − The pattern describing where each split should occur.
  • limit (optional) − The non-negative integer specifies the number of substring to be included into an array.

Return value

This method returns an array of string.

Example 1

If we omit the limit parameter and pass only the separator parameter to this method, it will divide the string based on the specified separator.

In this example, we are using JavaScript split() method to divide the string "Tutorials Point" based on a specified separator and retrieve an array containing the separated substrings.



JavaScript String split() Method





Output

The above program returns an array containing separated substrings:

String: Tutorials Point
Separator:
An array containing substrings: Tutorials,Point

Example 2

If both separator and limit parameters are passed, the method divides the current string based on the specified separator and includes substrings into an array based the specified number of limit.

The following is another example of the JavaScript string split() method. We use this method to divide the current string "Welcome to Tutorials Point" based on the specified separator "o" and include the separated substring into an array based on the specified number of limit 2.



JavaScript String split() Method





Output

After executing the above program, it returns an array containing separated substring as −

String: Welcome to Tutorials Point
Separator: o
Limit: 2
An array containing substrings: Welc,me t

Example 3

In the given example, we use the split() method to divide and retrieve an array containing the separated substring based on the specified limit and separator. We iterate through each element of the returned array and print them.



JavaScript String split() Method





Output

Once the above program is executed, it displays the following output −

String: Welcome to Tutorials Point
Separator:
Limit: 3
The returned array: WelcometoTutorials
Advertisements