Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 12, 2021 07:44 am GMT

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.

Lets 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 sentencelet 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

Lets 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. Lets 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 characterconsole.log(sentence.split(' '));//Result://(11)['_We', 'want', 'to', 'count', 'the', 'number', 'of', 'words', 'in', 'this', 'sentence']//2. Case with a stringconsole.log(sentence.split('to'));//Result: //(2)['_We want ', ' count the number of words in this sentence']//3. Case without spearatorconsole.log(sentence.split());//Result: //['_We want to count the number of words in this sentence']//4. Case on the beggining or the endconsole.log(sentence.split('_'));//Result://(2)['', 'We want to count the number of words in this sentence']//5. Empty string separatorconsole.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 doesnt 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 integerconsole.log(str.split(' ', 3));//Result://(3) ['Split', 'this', 'string']//2. Case If limit is equal 0console.log(str.split(' ', 0));//Result://[]//3. Case More items than limitconsole.log(str.split(' ', 1));//Result://['Split']//4. Case when array contains less than the limitconsole.log(str.split(' ', 9));//Result://(3) ['Split', 'this', 'string']

RegEx as separator

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

Using RegEx as our separator can help us split a string by some pretty cool criteria. Lets 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 myTwitter, or you can read some of my other articles likeThe power of JavaScript slice method.


Original Link: https://dev.to/amersikira/how-to-use-the-split-method-in-javascript-2m97

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To