Last updated: Jan 2, 2023 Reading time · 5 min
# Table of Contents
- Handling a comma followed by a variable number of spaces
- Convert a comma-separated string to an Array of Numbers
Use the String.split() method to convert a comma-separated string to an array.
The split() method will split the string on each occurrence of a comma and will return an array containing the results.
We used the String.split() method to split a string into an array.
If the words in your string are separated by a comma followed by a space, pass a comma and a space as the separator to the split() method.
If the split() method is called on an empty string, it returns an array containing an empty string.
If you want to get an empty array when the string is empty, use the Array.filter() method.
The filter method returns a new array containing only the elements that meet the condition.
# Handling a comma followed by a variable number of spaces
If your string might contain a comma followed by one or more spaces, pass a regular expression to the String.split() method.
The forward slashes / / mark the beginning and end of the regular expression.
The brackets  are called a character class and match the specified characters.
In our case, spaces and commas.
The plus + matches the preceding item (spaces and commas) one or more times.
If you need to get an array of numbers, use the map() method.
The function we passed to the Array.map() method gets called with each element in the array.
On each iteration, we use the Number constructor to convert the current value to a number and return the result.
The map() method returns a new array containing the values returned from the callback function.
# Convert a comma-separated string to an Array of Numbers
To convert a comma-separated string to a numeric array:
- Use the split() method to split the string into an array of digits.
- Use the map() method to iterate over the array.
- Convert each string to a number and return the result.
We used the String.split() method to split the string on each comma.
The split() method divides a string into an array of substrings based on a separator.
By splitting the string on each comma, we get an array containing the digits.
The last step is to convert each string in the array to a number.
On each iteration, we use the Number() constructor to convert the string to a number and return the result.
In this example, our string contains empty values between the commas, some letters and punctuation.
The function we passed to the Array.filter method gets called with each element in the array.
The filter() method returns a new array that only contains the elements that meet the condition.
We first check if the element is equal to an empty string or contains only whitespace and return false if it does.
Finally, we use the isNaN function to check if the provided string is not a number.
We used the logical NOT (!) operator to negate the value returned from the isNaN() function.
The isNaN (is not a number) method tries to convert the string to a number and returns true if it fails.
This is why we used the trim() method to trim the string and verify that it's not an empty string.
We know that if the isNaN function gets called with a string that contains at least 1 character and returns true , the string is NOT a valid number.
Conversely, if the isNaN function gets called with a string that contains at least 1 character and returns false , then the string is a valid number.
Here are some more examples of calling isNaN with strings.
Only numeric values are contained in the array that the filter() method returns.
This enables us to call the map() method on the array to convert each string to a number.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
- Add a Space between the Characters of a String in JS
- Add a String to Beginning and End of another String in JS
Copyright © 2023 Borislav Hadzhiev
Answer: Use the split() Method
Here are some more FAQ related to this topic:
- How to display all items or values in an array using loop in jQuery
Is this website helpful to you? Please give us a like , or share your feedback to help us improve . Connect with us on Facebook and Twitter for the latest updates.
- DSA with JS - Self Paced
- JS Operator
- JS Examples
- JS Questions
- JS Tutorial
- Explore Our Geeks Community
- How to search the max value of an attribute in an array object ?
- How to call the map method only if the element is an array?
- using Array.from() and .split() method
The split() method is used to split a string on the basis of a separator. This separator could be defined as a comma to separate the string whenever a comma is encountered. This method returns an array of strings that are separated.
This approach involves iterating through each character in the string and checking for the comma. A variable previousIndex is defined which keeps track of the first character of the next string. The slice method is then used to remove the portion of the string between the previous index and the current location of the comma found. This string is then pushed onto a new array. This process is then repeated for the whole length of the string. The final array contains all the separated strings.
Method 3: Using Array.from() and .split() method
Example: In this example, we will use Array.from() and .spilt() methods to split the strings and convert them to an array.
Please Login to comment...
- Web Technologies
Please write us at contrib[email protected] to report any issue with the above content
Improve your Coding Skills with Practice
Split the words:
Split the words, and return the second word:
Split the characters, including spaces:
Use the limit parameter:
More examples below.
The split() method splits a string into an array of substrings.
The split() method returns the new array.
The split() method does not change the original string.
If (" ") is used as separator, the string is split between words.
The slice() Method
The substr() Method
The substring() Method
Split a string into characters and return the second character:
Use a letter as a separator:
If the separator parameter is omitted, an array with the original string is returned:
split() is an ECMAScript1 (ES1) feature.
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Top references, top examples, get certified.
In general, a string represents a sequence of characters in a programming language.
- Using the string literal as a primitive
- Using the String() constructor as an object
The image below represents the same thing:
In this article will learn about a handy string method called split() . I hope you enjoy reading it.
The split() method splits (divides) a string into two or more substrings depending on a splitter (or divider). The splitter can be a single character, another string, or a regular expression.
After splitting the string into multiple substrings, the split() method puts them in an array and returns it. It doesn't make any modifications to the original string.
Let's understand how this works with an example. Here is a string created using string literals:
We can call the split() method on the message string. Let's split the string based on the space ( ' ' ) character. Here the space character acts as a splitter or divider.
The main purpose of the split() method is to get the chunks you're interested in from a string to use them in any further use cases.
How to Split a String by Each Character
You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.
💡 Please note that splitting an empty string('') using an empty string as the splitter returns an empty array. You may get this as a question in your upcoming job interviews!
How to Split a String into One Array
You can invoke the split() method on a string without a splitter/divider. This just means the split() method doesn't have any arguments passed to it.
When you invoke the split() method on a string without a splitter, it returns an array containing the entire string.
💡 Note again, calling the split() method on an empty string('') without a splitter will return an array with an empty string. It doesn't return an empty array.
Here are two examples so you can see the difference:
How to Split a String Using a Non-matching Character
Usually, we use a splitter that is part of the string we are trying to split. There could be cases where you may have passed a splitter that is not part of the string or doesn't match any part of it. In that case, the split() method returns an array with the entire string as an element.
In the example below, the message string doesn't have a comma (,) character. Let's try to split the string using the splitter comma (,).
💡 You should be aware of this as it might help you debug an issue due to a trivial error like passing the wrong splitter in the split() method.
How to Split with a Limit
If you thought that the split() method only takes the splitter as an optional parameter, let me tell you that there is one more. You can also pass the limit as an optional parameter to the split() method.
As the name indicates, the limit parameter limits the number of splits. It means the resulting array will only have the number of elements specified by the limit parameter.
In the example below, we split a string using a space (' ') as a splitter. We also pass the number 4 as the limit. The split() method returns an array with only four elements, ignoring the rest.
How to Split Using Regex
We can also pass a regular expression (regex) as the splitter/divider to the split() method. Let's consider this string to split:
Let's split this string at the period (.), exclamation point (!), and the question mark (?). We can write a regex that identifies when these characters occur. Then we pass the regex to the split() method and invoke it on the above string.
The output looks like this:
You can use the limit parameter to limit the output to only the first three elements, like this:
💡 If you want to capture the characters used in the regular expressions in the output array, you need to tweak the regex a bit. Use parenthesis to capture the matching characters. The updated regex will be /([.,!,?])/ .
How to Replace Characters in a String using Split() Method
You can solve many interesting problems using the split() method combined with other string and array methods. Let's see one here. It could be a common use case to replace all the occurrences of a character in the string with another character.
For example, you may want to create the id of an HTML element from a name value. The name value may contain a space (' '), but in HTML, the id value must not contain any spaces. We can do this in the following way:
Consider the name has the first name (Tapas) and last name (Adhikary) separated by a space. Here we first split the name using the space splitter. It returns an array containing the first and last names as elements, that is ['Tapas', 'Adhikary'] .
Then we use the array method called join() to join the elements of the array using the - character. The join() method returns a string by joining the element using a character passed as a parameter. Hence we get the final output as Tapas-Adhikary .
ES6: How to Split with Array Destructuring
ECMAScript2015 (ES6) introduced a more innovative way to extract an element from an array and assign it to a variable. This smart syntax is known as Array Destructuring . We can use this with the split() method to assign the output to a variable easily with less code.
Here we split the name using the space character as the splitter. Then we assign the returned values from the array to a couple of variables (the firstName and lastName ) using the Array Destructuring syntax.
Before We End...
👋 Do you want to code and learn along with me? You can find the same content here in this YouTube Video. Just open up your favorite code editor and get started.
Let's connect. You will find me active on Twitter (@tapasadhikary) . Please feel free to give a follow.
You may also like these articles:
- 10 DevTools tricks to help you with CSS and UX design
- 10 trivial yet powerful HTML facts you must know
- 10 VS Code emmet tips to make you more productive
Writer . YouTuber . Creator . Mentor
If you read this far, thank the author to show them you care. Say Thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- English (US)
The split() method of String values takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
The pattern describing where each split should occur. Can be undefined , a string, or an object with a Symbol.split method — the typical example being a regular expression . Omitting separator or passing undefined causes split() to return an array with the calling string as a single element. All values that are not undefined or objects with a @@split method are coerced to strings .
A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified separator , but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.
- The array may contain fewer entries than limit if the end of the string is reached before the limit is reached.
- If limit is 0 ,  is returned.
An Array of strings, split at each point where the separator occurs in the given string.
If separator is a non-empty string, the target string is split by all matches of the separator without including separator in the results. For example, a string containing tab separated values (TSV) could be parsed by passing a tab character as the separator, like myString.split("\t") . If separator contains multiple characters, that entire character sequence must be found in order to split. If separator appears at the beginning (or end) of the string, it still has the effect of splitting, resulting in an empty (i.e. zero length) string appearing at the first (or last) position of the returned array. If separator does not occur in str , the returned array contains one element consisting of the entire string.
If separator is an empty string ( "" ), str is converted to an array of each of its UTF-16 "characters", without empty strings on either ends of the resulting string.
Note: "".split("") is therefore the only way to produce an empty array when a string is passed as separator and limit is not 0 .
If separator is a regexp that matches empty strings, whether the match is split by UTF-16 code units or Unicode code points depends on if the regex is Unicode-aware .
If separator is a regular expression with capturing groups, then each time separator matches, the captured groups (including any undefined results) are spliced into the output array. This behavior is specified by the regexp's Symbol.split method.
If separator is an object with a Symbol.split method, that method is called with the target string and limit as arguments, and this set to the object. Its return value becomes the return value of split .
Any other value will be coerced to a string before being used as separator.
When the string is empty and a non-empty separator is specified, split() returns [""] . If the string and separator are both empty strings, an empty array is returned.
The following example defines a function that splits a string into an array of strings using separator . After splitting the string, the function logs messages indicating the original string (before the split), the separator used, the number of elements in the array, and the individual array elements.
This example produces the following output:
Removing spaces from a string
In the following example, split() looks for zero or more spaces, followed by a semicolon, followed by zero or more spaces—and, when found, removes the spaces and the semicolon from the string. nameList is the array returned as a result of split() .
This logs two lines; the first line logs the original string, and the second line logs the resulting array.
Returning a limited number of splits
In the following example, split() looks for spaces in a string and returns the first 3 splits that it finds.
Splitting with a RegExp to include parts of the separator in the result
If separator is a regular expression that contains capturing parentheses ( ) , matched results are included in the array.
Note: \d matches the character class for digits between 0 and 9.
Using a custom splitter
An object with a Symbol.split method can be used as a splitter with custom behavior.
The following example splits a string using an internal state consisting of an incrementing number:
The following example uses an internal state to enforce certain behavior, and to ensure a "valid" result is produced.
- Polyfill of String.prototype.split in core-js with fixes and implementation of modern behavior like Symbol.split support
- Regular expressions guide
Creating arrays by using split method of a string by using delimiter
Breaking without any delimiter
Adding option to limit the array, breaking email address using split.
Post your comments , suggestion , error , requirements etc here