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 return…


This content originally appeared on DEV Community and was authored by Amer Sikira

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

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', ' ', ...]

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']

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", "." ]

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.


This content originally appeared on DEV Community and was authored by Amer Sikira


Print Share Comment Cite Upload Translate Updates
APA

Amer Sikira | Sciencx (2021-10-12T07:44:16+00:00) How to use the split method in JavaScript. Retrieved from https://www.scien.cx/2021/10/12/how-to-use-the-split-method-in-javascript/

MLA
" » How to use the split method in JavaScript." Amer Sikira | Sciencx - Tuesday October 12, 2021, https://www.scien.cx/2021/10/12/how-to-use-the-split-method-in-javascript/
HARVARD
Amer Sikira | Sciencx Tuesday October 12, 2021 » How to use the split method in JavaScript., viewed ,<https://www.scien.cx/2021/10/12/how-to-use-the-split-method-in-javascript/>
VANCOUVER
Amer Sikira | Sciencx - » How to use the split method in JavaScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/10/12/how-to-use-the-split-method-in-javascript/
CHICAGO
" » How to use the split method in JavaScript." Amer Sikira | Sciencx - Accessed . https://www.scien.cx/2021/10/12/how-to-use-the-split-method-in-javascript/
IEEE
" » How to use the split method in JavaScript." Amer Sikira | Sciencx [Online]. Available: https://www.scien.cx/2021/10/12/how-to-use-the-split-method-in-javascript/. [Accessed: ]
rf:citation
» How to use the split method in JavaScript | Amer Sikira | Sciencx | https://www.scien.cx/2021/10/12/how-to-use-the-split-method-in-javascript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.