Home / Blog /
How to Use split in JavaScript
//

How to Use split in JavaScript

//
Tabnine Team /
4 minutes /
November 3, 2020

The split() method takes a string and returns an array of strings, splitting the original string based upon a provided separator character.

This can be useful when only a certain portion of a string is required. For example, when getting a specific cookie or when iteration is required.

Note: The split() method does not change the original string. Remember – JavaScript strings are immutable.

The split method divides a string into a set of substrings, maintaining the substrings in the same order in which they appear in the original string. The method returns the substrings in the form of an array.

Basic split() usage

The code below demonstrates how to use the split() method:

const str = 'Form an array from this string';

const arrCopy = str.split();
console.log(arrCopy);
// expected output: ["Form an array from this string"]

const words = str.split(' ');
console.log(words);
// expected output: ["Form", "an", "array", "from", "this", "string"]

The above example demonstrates two different possible results from the split() method:

  1. The first example demonstrates what happens when you do not provide a separator. When no separator is provided, the return value is an array with a single element. This element contains the entire original string.
  2. The second example provides the space character (‘ ‘) as the separator, and the resulting array contains six elements – one for each word in the original string.

Syntax

The syntax of the split() method is as follows:

str.split(separator, limit)

  • separator (optional): the separator is a pattern that will be used to divide the string (e.g. blank spaces, semicolons, http:// etc.).
  • limit (optional): the limit defines how many splits occur before the function stops executing.

Let’s start with the limit parameter, as it is a bit easier to understand. Take the below code, which uses the same test string from our previous example:

const firstWords = str.split(' ', 3);
console.log(firstWords);
// expected output: ["Form", "an", "array"]

In this code we provided a value of 3 to the limit parameter. After three splits have taken place, the function has finished its job, and an array consisting of the first three substring elements is returned.

Separator

In our first example above, we called the split() method with no parameter, and assigned the result to arrCopy. As we did not provide a separator, the return value was a copy of the original string stored in an array.

When a separator is provided, the array will include a set of substrings of the original string. Each substring ends when the pattern is found, and does not include the separator pattern itself. As seen in the words array from the above example, when provided with a separator representing a blank space the result was an array with each of the words in the string stored as an individual element. Note that no blank spaces were included in the result strings.

If there was an extra blank space between one of the words, e.g. between array and from, the split() method would have added an empty string as one of the return values. The result of this call would have been : [“Form”, “an”, “array”, “”, “from”, “this”, “string”].

The separator parameter allows the use of regular expressions.

Using a RegEx as the separator

Below is an example of using a RegEx as the separator in a call to split(). With RegEx parameters, s stands for whitespace and matches any whitespace character (e.g. space, tabs, line breaks, and so on).

const arrRegEx= str.split(/(s)/);
console.log(arrRegEx);  
// expected output: ["Form", " ", "an", " ", "array", " ", "from", " ", "this", " ", "string"]

Note: When using RegEx that contains capturing parentheses, the pattern is included in the result, and whitespaces appear as elements in the array!

To prevent this, remove the capturing parentheses from the provided RegEx. The result will then appear exactly as it does when we provide the blank space as a separator:

const arrRegEx2 = str.split(/s/);
console.log(arrRegEx2);
// expected output: ["Form", "an", "array", "from", "this", "string"]

RegExes can be very useful, particularly when you need to use more than one separator. For example, if you need to split a string apart based upon the sentences it contains, you will need to search the string for multiple different punctuation marks. The example below demonstrates how to do so:

const str = 'Hey there! Wait, Tim? Tim from LCU? I just saw Wendy down the road.';
const sentences = str.split(/['!,?,.,,']/);
console.log(sentences); 
// expected output: ["Hey there", " Wait", " Tim", " Tim from LCU", " I just saw Wendy down the road", ""]

As we can see, the string was split into substrings based on the provided punctuation marks. If the punctuation marks are also needed, simply add the capturing parentheses to the regex.

Tip: to edit out the blank spaces at the beginning of the sentences use the array iteration method map() to apply the trim() method to each sentence.

Split with Array as separator

You can also pass an array as the value for the separator parameter. When doing so, the array is converted to a string before being used as a separator, as in the example below:

const nameStr = 'Kelly, Dan, Michael, Sharon, John';
const nameArr = nameStr.split([', ']);
console.log(nameArr); // expected output: ["Kelly", "Dan", "Michael", "Sharon", "John"]

 

Related Articles

JavaScript – How to Use The Array map() Method

JavaScript – How to Use the toUpperCase() Method

JavaScript – How to Use the alert method