The JavaScript split() function splits the original string into an array of substrings based on the specified separator and returns them in an array. It is useful to convert a string to an array.
The split() function searches for a pattern inside an original string, and once it is found, it divides the text into an array of individual items. Remember, it will not alter the original string.
JavaScript split() function syntax
The syntax of the string split() function is shown below.
String_Object.split(Separator, limit)
If you observe the syntax, the split() function accepts two arguments.
- Separator: It defines how the string should be split or divided. It can be a simple text or a Regular Expression. For example, empty string, space, ‘,’, ‘.’, word, character, or regular expression.
- Limit (integer): It is an optional parameter. It restricts the number of elements written in the array. It limits the total number of substrings returned by the split() function inside an array.
From the above JavaScript split() function syntax, both the separator and limit are optional arguments.
- If you ignore the first argument (separator), the split function returns the complete string as a single array item.
- When the separator is an empty string, the split() method returns an array of individual characters in a string.
- If you omit the second argument (limit), split starts from the beginning and continues until the end. If we set the limit to 0, the split() function returns an empty array ([]).
Return Value: The JavaScript split() function does not modify the original string and returns an array as the output. If the original string is empty, the split() function returns an array with one empty string.
- If the separator is a string, it returns an array of strings split by the given separator.
- If the separator is a regular expression, it returns an array of strings and captured groups.
JavaScript split function examples
The following examples demonstrate the working functionality of the substring() function with or without a separator and with/without a limit parameter. Before going into the example, let me explain how the split() method works internally.
First, the split() function reads the given string and searches for a separator. If found, it breaks the original string into individual substrings based on a separator. Next, it creates a new array and stores those substrings inside it.
JavaScript split by Comma Delimiter
In the example below, we declare a string of fruits, with each fruit separated by a comma delimiter. In the next line, we used the split() function with a single argument.
As we have specified a comma as the separator, the split() function searches for a comma inside the original string. If it is found, that portion of a text is added as an array item. The process continues until there is no comma.
let str = 'apple,kiwi,banana,orange';
let a = str.split(',');
console.log(a);
[ 'apple', 'kiwi', 'banana', 'orange' ]
Once the array has returned, we can use a for loop, a while loop, or a do while loop to iterate over the array of strings and perform further operations. Otherwise, use the index position to access an individual item.
console.log(a[0]); console.log(a[1]);
apple
kiwi
Split by spaces
In general, a string is a group of words separated by white space. There are many situations where we have to split the given string based on this space.
In the example below, we declare a string of four words. In the next line, we use the split() function and pass the blank space as the first argument. Whenever the JavaScript split() function finds a whitespace, it creates a new array item with that specific word.
Finally, the split() function will convert the given string into an array of four items, and each item is a word from the original string.
let str = 'Apple Launching New iPhone';
let a = str.split(' ');
console.log(a);
[ 'Apple', 'Launching', 'New', 'iPhone' ]
JavaScript split a string into individual characters
If the original string is non-empty, and when we pass an empty string as a split() function argument, it converts the string into an array of individual characters. If you observe it below, the split function returns an array of eight items. Each item is a character from the original string, including a blank space.
let str = 'New Year';
let a = str.split("");
console.log(a);
[
'N', 'e', 'w',
' ', 'Y', 'e',
'a', 'r'
]
JavaScript split string function with arguments
This example will help you understand this split method. Here, we declared an str variable with a sentence.
The first statement will break the original text into individual characters. Next, we used the empty space as a separator for the split function. So, it will separate the original str1 into an array of words based on white space.
In the fourth statement, we used the second argument to restrict the JavaScript array output to four. Next, we used the substring “abc” as a separator for this String method. Here, i is the regular expression to perform case insensitive search.
<!DOCTYPE html>
<html>
<head>
<title> Example</title>
</head>
<body>
<h1> JsExample </h1>
<script>
var Str1 = "We are Abc working in abc company since abc years";
var Str2 = Str1.split("");
var Str3 = Str1.split(" ");
var Str4 = Str1.split(" ", 4);
var Str5 = Str1.split(/abc/i);
var Str6 = Str1.split(/abc/i, 2);
document.write(Str2 + "<br \>");
document.write(Str3 + "<br \>");
document.write(Str4 + "<br \>");
document.write(Str5 + "<br \>");
document.write(Str6 + "<br \>");
</script>
</body>
</html>

Splitting an empty string
When working with an empty string, you must be careful with the JavaScript split() function return value.
- If we pass the separator (first argument) as the empty string, it returns an empty array.
- If we pass any delimiter, such as a comma as the separator, it returns an array of one item, and that item is an empty string.
In the example below, we declared an empty string and used the split() function with a comma and an empty string separator.
let str = ''
let a = str.split(',')
console.log(a);
let b = str.split('');
console.log(b);
[ '' ]
[]
JavaScript split by a word
We can use anything as a separator for the split() function. In the previous examples, we have used a comma, a space, and so on as the separators. However, we can use a word or any other character sequence as the separator to break the string into an array of substrings.
In the following example, we declared a string of seven words. As you can see, there is a repetition of the word ‘abc’. Next, we used the split() function to split the given string into an array of words based on ‘abc’.
let str = 'We abc look abc at abc World';
let a = str.split('abc');
console.log(a);
[ 'We ', ' look ', ' at ', ' World' ]
JavaScript split() function and trim() to remove spaces
If you observe the above example output, it splits the given string based on the word ‘abc’. However, there are extra spaces on every array item because there are spaces before and after the ‘abc’.
To avoid these unwanted spaces, we must use the built-in trim() function in combination with the map object. Here, the map function assigns the trim() function to each array item.
let str = 'We abc look abc at abc World';
let a = str.split('abc').map(c => c.trim());
console.log(a);
[ 'We', 'look', 'at', 'World' ]
Use split to convert multiline text into an array of strings
If there is a multiline text, we can use the newline (\n) character as the separator to split the string. The script below splits the multiline text and considers each line as one array item.
const multiLines = `This is a First line
Second line
Third line
Fourth Line
Fifth Line End`;
const lines = multiLines.split('\n');
console.log(lines);
[
'This is a First line',
'Second line',
'Third line',
'Fourth Line',
'Fifth Line End'
]
What if a split separator is not found in a string?
As we all know, the JavaScript split() function uses a separator to convert a string into an array of items. When we use a non-existent separator to split the string, it returns the complete string as one array item.
In the example below, we used a string of two words separated by a whitespace. However, the split() function uses a comma as a separator to split the string. As it does not find any commas inside a string to split, it simply treats the whole string as one item.
let str = 'Apple iPhone';
console.log(str.split(','));
[ 'Apple iPhone' ]
TIP: When you use the wrong separator, there will be no string splitting.
JavaScript split function with a regular expression
A regular separator is useful for a normal string separated by a uniform delimiter, word, or character sequence. However, if there is no uniformity in the word separator or multiple separators, we must use a regular expression.
Split by multiple separators
A string may have multiple separators, and the split() function supports dividing it based on multiple separators. In the example below, there is a comma, full stop, semicolon, pipe, and – symbols. Here, we must pass all of them in a regular expression. If any of the separator matches, split the text.
let str = 'Apple,Samsung.Mobile|Laptop;800-3000';
let a = str.split(/[,.|;-]/);
console.log(a);
[ 'Apple', 'Samsung', 'Mobile', 'Laptop', '800', '3000' ]
JavaScript split function handling multiple spaces string
If a given string is separated evenly by a single or multiple spaces, we can use the same technique to split it. However, if there are uneven spaces, we must use a regular expression.
In the example below, the declared starting has four words, and each word is separated by an uneven space. In such a situation, use the regular expression. Here, \s represents the spaces and + means one or more space characters. To show the difference, we used the regular split() function with a whitespace separator.
let str = 'Samsung Mobile Manufacturing Company';
let a = str.split(/\s+/);
console.log(a);
console.log(str.split(' '));
[ 'Samsung', 'Mobile', 'Manufacturing', 'Company' ]
[ 'Samsung Mobile', 'Manufacturing', '', 'Company' ]
Use regular expressions to separate by numbers
In the following JavaScript split() function example, each word is separated by two or more digits. In such a case, we can use a regular expression as a separator. Here, [0-9] means the numbers, and the + symbol means one or more digits. So, if the split() function found one or more digits, split the text based on that number.
let str = 'Apple17Samsung26Mobile800Laptop3000PC';
let a = str.split(/[0-9]+/);
console.log(a);
[ 'Apple', 'Samsung', 'Mobile', 'Laptop', 'PC' ]
Preserve the separator after split
When working with the JavaScript split() function with a regular expression as the first argument, we can preserve the separator. To do so, we must place the regular expression inside brackets (). The paranthesis creates a capture group that includes the separator in the array of strings output.
let str = '31-12-2025';
let a = str.split(/(-)+/);
console.log(a);
[ '31', '-', '12', '-', '2025' ]
JavaScript split() function with a limit
As we earlier mentioned, the split() function has a second argument to limit the total number of splits. When we pass a limit value of 3, the result array must have only three substrings. Once those three items are received, the splitting process stops.
In the example below, we declared a string of five countries, each separated by a whitespace. The first statement is a regular JavaScript split() function example with a whitespace as the separator. So, it splits the string into an array of five countries. The second statement uses a second parameter (limit) and sets it to 1. It means the split has to stop after one array item.
let str = 'USA UK INDIA CANADA FRANCE';
console.log(str.split(' '));
let a = str.split(' ', 1);
console.log(a);
[ 'USA', 'UK', 'INDIA', 'CANADA', 'FRANCE' ]
[ 'USA' ]
To understand the limit argument better, we use different limit values.
console.log(str.split(' ', 1));
console.log(str.split(' ', 2));
console.log(str.split(' ', 3));
console.log(str.split(' ', 4));
console.log(str.split(' ', 5));
[ 'USA' ]
[ 'USA', 'UK' ]
[ 'USA', 'UK', 'INDIA' ]
[ 'USA', 'UK', 'INDIA', 'CANADA' ]
[ 'USA', 'UK', 'INDIA', 'CANADA', 'FRANCE' ]
Set limit 0
If we set the limit to 0, the split() function returns an empty array ([]).
let str = 'New Year';
let a = str.split('', 0);
console.log(a);
[]
JavaScript split() function real-time examples
The following are some examples at the production level, and we will explain them in detail. If you find any other examples, email us to add them.
ES6: Use JavaScript split() function with array destruction
ES6 introduced a smarter way to extract array items and assign them to a variable. In the following example, we use the array destructing technique to assign the array of strings returned by the split () function.
let str = 'John Miller';
let [firstName, LastName] = str.split(' ');
console.log(firstName);
console.log(LastName);
John
Miller
Use split to Extract the First Name of an employee
We can use the JavaScript split function with two parameters to extract the first name or first word from a sentence. From the example below, we declared a string with the first name, middle name, and last name.
In the next line, we use the split function with space as the separator and an integer 1 as the limit volume. It means it has to split the given string based on the white spaces. However, it should limit the number of splits to one and eventually return the first name (word).
let str = 'David Miller Junior'
let a = str.split(' ', 1)
console.log(a);
console.log(a[0]);
[ 'David' ]
David
Use JavaScript split() function for Word Counter
Word counting is the most common scenario when writing any document, including a blog post or an article. We can use a combination of string functions to count the total number of words in a given sentence or paragraph.
In the example below, the trim() function removes the extra spaces on both sides. The split function with the regular expression splits the given sentence based on the blank spaces. The length property finds the total number of items in a generated array.
function wordCount(text)
{
return text.trim().split(/\s+/).length;
}
let str = 'New Apple iPhone expected to launch in September 2026';
console.log(wordCount(str));
9
JavaScript split() function to Reverse a string
As there is no built-in function to reverse a string, we must do some work to achieve this. The combination of the string split() function, array reverse(), and join() method helps to reverse a given string.
In the example below,
- str.split(”) means an empty string passed as the separator. So, the split() function converts the given string into an array of individual characters.
- reverse(): It is an exclusive array function that reverses the given array. Here, it reverses the individual characters in the array generated by the split() function.
- join(): It joins those reversed characters into a string. In simple words, it converts the revered array of characters into a string.
function stringReverse(str)
{
return str.split('').reverse().join('');
}
let s = 'Happy Coding'
console.log(stringReverse(s));
gnidoC yppaH
How to reverse words in a sentence using split?
In the above example, we have shown how to reverse a string. In this section, we show how to reverse words in a given string. With a simple tweak to the above example, we can achieve it.
Within the JavaScript split() function, replace the empty string separator with a whitespace separator and add a blank space in the join() function.
function stringWordReverse(str)
{
return str.split(' ').reverse().join(' ');
}
let s = 'Happy New Year'
console.log(stringWordReverse(s));
Year New Happy
Removing empty values by split
One of the common problems is removing the empty values in a string after converting it to an array. In the example below, we declared a string with some empty information (city and Birth Date).
The JavaScript split() function splits the employee information using a comma delimiter. As there are two extra commas, it treats them as an empty string of words. The filter() function with a Boolean argument removes the False records from the given array. JavaScript considers empty string, 0, Null, NaN, false, and undefined as falsy values, so filter() removes them from the array.
let str = 'John,25,,Engineer,,100000'
let a = str.split(',')
console.log(a);
let b = a.filter(Boolean);
console.log(b);
[ 'John', '25', '', 'Engineer', '', '100000' ]
[ 'John', '25', 'Engineer', '100000' ]
Preserve empty values using split() method
In the above JavaScript split() function example, we removed the empty values in a string. However, it is advisable to keep them as N/A because the next line may have those values, and it will be difficult to match them. In the example below, we used the map() function with Logical OR to let values as they are and replace any empty items with ‘N/A’.
let str = 'John,25,,Engineer,,100000';
let a = str.split(',').map((c) => c || 'N/A');
console.log(a);
[ 'John', '25', 'N/A', 'Engineer', 'N/A', '100000' ]
Remove spaces from the user input
The following script allows the user to insert tag values or any text separated by a comma. Sometimes, a user may accidentally add extra white spaces between the words. The JavaScript split() function splits the tags by a comma delimiter, and the trim() function removes the spaces.
let str = prompt('Enter Tgas');
let a = str.split(',').map((word => word.trim()));
console.log(a);
seo, seo meta, new , tool , text
Array(5) [ "seo", "seo meta", "new", "tool", "text" ]
JavaScript split and extracting CSV data
In the following example, we declared a CSV of user information. The split() function uses a comma delimiter as the separator to split the string into an array of substrings.
The console statement uses the array index positions to show the user’s information. We can declare a variable to assign the individual information and use it later in the program. For instance, let age = a[2].
let userCSV = 'John,Miller,30,jmiller@example.com,90000,Engineer';
let a = userCSV.split(',');
console.log(a);
console.log("FirstName = " + a[0]);
console.log("LastName = " + a[1]);
console.log('Age = ' + a[2]);
console.log('Email = ' + a[3]);
console.log('Income = ' + a[4]);
console.log('Profession = ' + a[5]);
[ 'John', 'Miller', '30', 'jmiller@example.com', '90000', 'Engineer' ]
FirstName = John
LastName = Miller
Age = 30
Email = jmiller@example.com
Income = 90000
Profession = Engineer
Extract the Username and Domain from Email using split
In the following example, we use the JavaScript split function to divide the given email using the @ symbol. Next, we utilized the ES6 array destruction concept to assign the username and domain information.
let str = 'contact@tutorialgateway.org';
let [username, domain] = str.split('@');
console.log(username);
console.log(domain);
contact
tutorialgateway.org
Difference between the string slice() and split() functions?
Although the names look similar, they are different.
- split(): It splits the given string into an array of substrings.
- slice(): It extracts a portion of a given string.
The following examples use the JavaScript split() and slice() functions on the same string to see the return value.
let str = 'New Year';
console.log(str.split(' '));
console.log(str.slice(0, 3));
[ 'New', 'Year' ]
New
Difference between JavaScript split() and join()
As we said earlier, the split() divides the original string based on the given separator and returns an array. In simple terms, it converts a string into an array of substrings. The join() function converts an array into a string.
The following example uses the split() and join() functions to perform the string replacement. Here, the split() converts the given string into an array of three items. Next, the join() converts back to a string by appending —.
let str = 'New Year Celebrations';
let a = str.split(' ');
console.log(a);
let b = a.join('---')
console.log(b);
[ 'New', 'Year', 'Celebrations' ]
New---Year---Celebrations