Splitting strings with the split() method

Ronaldo B.July 27, 20226 min read

In this article

Manipulating strings is one of the most common tasks when programming. In this article, we will talk about one of the essential methods related to strings, the split() method. We will also identify the situations in which it can help us.

The split() method

This method converts a string into an array. We can say that it “cuts” a string into several “pieces,” which are the positions of the array to be returned. To perform this “cut” or separation in the string, the split() method relies on a delimiter that we provide as a parameter. This delimiter can be any character. When found, this delimiter is removed from the string.

If you're already familiar with another programming language, such as PHP, we can say that split() is like JavaScript’s “explode().”

To understand this concept well, nothing is better than a good example, right? So, let’s develop a few of them now!

Examples of the split() method

Let’s create a variable company that will contain a string:

let company = "Hcode Treinamentos Você especialista";

Let’s call the split() method on this variable, providing a space as a parameter, like this

company.split(' ');

The result of this code will be the following:

Return of the split() method

Notice that each space has been removed, and the returned array contains each of the words from our sentence. And since the return is an array, we can use any JavaScript method related to this type of data to manipulate this information.

But what if we wanted to see a specific number of words from this sentence, like just the first three words? This is also possible with the split() method. It expects a second parameter, which is the maximum number of positions that the returned array should have. In this case, we could use the following code:

company.split(' ', 3);

The return will be the following:

Return of the split() method

Excellent, only the first three words were returned. Quite interesting, isn’t it?

Just as we can see all the words from our sentence in an array, we can also see all the letters of it. To do this, simply provide an empty string to the split() method, like this:

company.split('');

The result will be this:

Return of the split() method

Imagine that we wanted to discover the number of vowels or consonants in this sentence. By using array methods in conjunction with the return of the split() method, we could perform this process in this case.

But let’s imagine a situation: what happens if we do not provide any parameter to the split() method? Let’s test this with the following code:

company.split();

The result will be the following:

Return of the split() method

Note that when we hide the delimiter for the string, the split() method still returns an array, but with only one position, which is the string itself.

So far, we have used spaces as delimiters in the split() method. But what happens if we provide a letter? To find out, let’s use the following code:

company.split('o');

The result will be this:

Return of the split() method

Note that all the letter “o” has been removed from the string, and the positions where this vowel was found in the sentence were turned into array indices. There are four items in the array. We know that the last position does not contain the given letter. Thus, we can conclude that this sentence has three letters “o.” See how many interesting situations the split() method can help us with.

Remember when we talked about the possibility of using methods related to arrays when working with split()? Let’s do an example of that now. Imagine we want to reverse the content of a sentence. We could do this with the following code:

company.split('').reverse().join('');

To explain: we performed the split() on the whitespace of the string. We’ve seen that this code will convert our string into an array of each of its letters. Then we provide the reverse() method, which, as the name suggests, performs the “reversal” of the array, i.e., inverts its positions. After that, we provide the join() method, which converts an array back into a string, exactly the opposite of split() ?.

The result of this code will be the following:

Return of the split() method in conjunction with the reverse() and join() methods

Our string was successfully reversed. Pretty cool, don’t you think?

Other situations where we can use split()

Perhaps we might ask ourselves: “But in what situations in everyday work could I use the split() method?” Besides the situations mentioned above, the split() method can be used when we have a string and wish to select only part of it.

For example: imagine that our user uploads a file and we want to dynamically know the name of this file and its extension. The split() method can help us. We know that the character that separates the name of the file from its extension is “.” (dot). Example: hcode.png.

Let’s create a function that performs this division for us. It will have the following structure:

function getNameAndExtensionFromFile(fileName) {
    let result = fileName.split('.');
    return {
        name: result[0],
        extension: result[1]
    };
}

Note that the name of the file will be in position 0 of the array, while the extension will be in position 1. Let’s call this function:

getNameAndExtensionFromFile('javascript.jpg');

The result of this function is the following:

Return of our function that uses the split() method

The information was returned correctly. If we wanted to insert this data into the database separately, everything would already be ready.

Let’s think of another situation: imagine that we have a table in our database that stores the emails of our registered users. However, in addition to saving the full email, we also want to register its domain (gmail.com, hotmail.com, etc.), to be able to convert this information into some kind of report in the future. How could we identify this information automatically when the user provides their email?

We know that the character that separates the username from its email domain is “@” (at symbol). Thus, we could have the following function:

function getUsernameAndDomainFromEmail(email) {
    let result = email.split('@');
    return {
        username: result[0],
        domain: result[1]
    };
}

Let’s call this function:

getUsernameAndDomainFromEmail('[email protected]');

The return would be the following:

Return of our function that uses the split() method

Excellent. We have access to the information of the email. The best part is that we didn’t need to use any type of substring for that. The split() method already returned what we wanted.

You can find all the codes developed in this article on our GitHub.

We used this method in one of the projects in our Complete HTML5 Course. You can check out a snippet from that lesson on our YouTube channel ?.

Also, if you wish to learn other incredible features of the JavaScript language and use them to create amazing projects, be sure to take our Complete JavaScript Course.

Until the next article :)

Keep learning with Hcode

Sign up for the course platform and follow the next blog guides.