How Does the split() Method Work in JavaScript?

Introduction

In JavaScript, there are comprehensive built-in methods available that make working with JavaScript easier. These methods are very useful, especially when working with strings. Today, we are going to talk about the split() method, which is particularly useful for splitting strings. Before we write any code, let's take a look at how it works. The split() method takes two arguments. The first argument specifies how to split the string into an array. However, the second argument is optional, and you can omit it, and most of the time we do that. We will learn more about this through examples.

How to split(‘’) String in JavaScript

Splitting a String into Characters:

JavaScript

copy

 let str = 'hello world'
 let strSplit = str.split('');
 console.log(strSplit)
 // output [ 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' ]

In the above example, I applied this method to a string, converting it into an array. I used only the first argument within the split('') method and omitted the second argument for now. However, don't worry, as I will use both arguments together in an upcoming example.

Let's focus on the code I wrote above. I used split('') with two single quotations without adding a space between them.

Note: It will work the same even if you use double quotation " instead of single quotation '.

Splitting a String into Words:

JavaScript

copy

 let str = 'hello world'
 let strSplit = str.split(' ');
 console.log(strSplit)
 // output [ 'hello', 'world' ]

This code looks similar to the code I used above. However, the output is different. The only difference is that I added a single space between the quotations. Surprisingly, this small change altered the functionality significantly. Adding a space between the quotations splits the string into words, creating a different pattern.

Limiting the Number of Parts:

JavaScript

copy

 let str = 'hello world'
 let strSplit = str.split('', 2);
 console.log(strSplit)
 // output [ 'h', 'e' ]

In this example, I used two arguments. In the first argument, I used single quotations without adding a space between them. This will iterate over each character one by one.

In the second argument, I used 2, which means it will iterate over the first two characters one by one.

Remember, by using split('', 0), the output will be an empty array. Likewise, if we use split(' ', 1), it will iterate over the first-word pattern since our string is str = 'hello world', and the output will be hello.

Splitting by Words with a Limit:

JavaScript

copy

 let str = 'hello world'
 let strSplit = str.split(' ', 1);
 console.log(strSplit)
 // output [ "hello" ]

In this case, the split(" ", 1) breaks the string into words but only includes the first word in the result.