DEV Community

Cover image for How to use the split method in JavaScript
Amer Sikira
Amer Sikira

Posted on • Originally published at webinuse.com

How to use the split method in JavaScript

This post was originally published on webinuse.com
We have already written about The power of JavaScript slice method which is often confused with the JavaScript split (.split()) method. .split() method is splits a string by certain criteria and returns an array of elements.

Let’s start from the beginning. We have a string that we want to split/divide by certain criteria. .split() method accepts two parameters: 1. separator and 2. limit. For example, we have a program that needs to count the number of words in the sentence, using JavaScript.

let sentence = "We want to count the number of words in this sentence";
console.log(sentence);
//Result: 
//We want to count the number of words in this sentence

let numberOfWords = sentence.split(" ");
console.log(numberOfWords)
//Result: 
/* (11) ['We', 'want', 'to', 'count', 'the', 'number', 
        'of', 'words', 'in', 'this', 'sentence']
*/

console.log(numberOfWords.length);
//Result: 
// 11

Enter fullscreen mode Exit fullscreen mode

Let’s break down our example. We store some sentence in a variable. It could be from anywhere, for that matter. Then, we used .split()method on the variable where our sentence was stored. After .split()was successfully over, it returned an array of elements, and the array .length was 11. This means we had 11 words in our sentence.

Separator

As we have mentioned earlier, JavaScript .split() accepts two parameters. The first one is the separator. The separator is actually the criteria by which our string is being split.

The separator can be a string or regular expression. Let’s discuss different cases of the separator.

  1. The easiest case is when the separator is a single character. This single character can be anything: letter, number, dash, comma, dollar sign, etc.
  2. When the separator contains multiple characters. In that case, exact match for those characters must be found in the same order in delimited string.
  3. If we use empty separator, or separator that is not in the string, then entire string is returned as single element of an array.
  4. According to MDN, if separator appears at the beginning (or end) of the string, it still has the effect of splitting. The result is an empty (i.e. zero length) string, which appears at the first (or last) position of the returned array.
  5. If we use empty string separator, than the string is converted to an array of each of its UTF-16 “characters”.

Now, we are going to give an example for each and every one of these points.


let sentence = "_We want to count the number of words in this sentence";

//1. Case with single character

console.log(sentence.split(' '));
//Result:
//(11)['_We', 'want', 'to', 'count', 'the', 'number', 'of', 'words', 'in', 'this', 'sentence']

//2. Case with a string
console.log(sentence.split('to'));
//Result: 
//(2)['_We want ', ' count the number of words in this sentence']

//3. Case without spearator
console.log(sentence.split());
//Result: 
//['_We want to count the number of words in this sentence']

//4. Case on the beggining or the end
console.log(sentence.split('_'));
//Result:
//(2)['', 'We want to count the number of words in this sentence']

//5. Empty string separator
console.log(sentence.split(''));
//Result: 
//(54)['_', 'W', 'e', ' ', 'w', 'a', 'n', 't', ' ', 't', 'o', ' ', ...]

Enter fullscreen mode Exit fullscreen mode

Limit

The limit parameter represents the maximum number of items we want to be returned. There is some rules regarding the limit parameter in JavaScript .split() method.

  1. The limit parameter must be positive integer
  2. If the limit is equal to zero, an empty array is returned
  3. If there are more items in an array than the actual limit, than .split() returns only up until limit. JavaScript .split() method doesn’t include any leftover data
  4. When array contains less data than actual limit, all data is returned
let str = "Split this string";

//1. Case Limit must be positive integer
console.log(str.split(' ', 3));
//Result:
//(3) ['Split', 'this', 'string']

//2. Case If limit is equal 0
console.log(str.split(' ', 0));
//Result:
//[]

//3. Case More items than limit
console.log(str.split(' ', 1));
//Result:
//['Split']

//4. Case when array contains less than the limit
console.log(str.split(' ', 9));
//Result:
//(3) ['Split', 'this', 'string']
Enter fullscreen mode Exit fullscreen mode

RegEx as separator

Every developer hates RegEx. And I’ve never met any developer that can do anything with RegEx without consulting documentation or some other helper. But we can’t deny that RegEx is super useful.

Using RegEx as our separator can help us split a string by some pretty cool criteria. Let’s imagine that we want to split a string by a number. That number is not always the same. That is when we can use RegEx.

let myString = 'Hello 1 word. Sentence number 2.'
let splits = myString.split(/(\d)/)

console.log(splits)
//Result:
// [ "Hello ", "1", " word. Sentence number ", "2", "." ]
Enter fullscreen mode Exit fullscreen mode

The JavaScript split method is one of the most useful methods when working with strings. One of the super cool things is that .split() method is simple to use, and the other is that we can use RegEx to split a string, not only characters.

If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like The power of JavaScript slice method.

Top comments (0)