Textual data is typically stored through sequences of characters - strings. These sequences, are ultimately, arrays, and converting between the two structures typically is both simple and intuitive. Whether you're breaking a word down into its characters, or a sentence into words - splitting a string into an array isn't an uncommon operation, and most languages have built-in methods for this task.
- Split String into Array with split()
The split() method is used to divide a string into an ordered list of two or more substrings, depending on the pattern/divider/delimiter provided, and returns it. The pattern/divider/delimiter is the first parameter in the method's call and can be a regular expression , a single character , or another string .
For example, suppose we have a string:
We could split it on each whitespace (breaking it down into words), or on every character, or any other arbitrary delimiter, such as 'p' :
One of the major downsides of using single characters or even entire strings is that the approach is fairly rigid. You can't match by multiple delimiters, unless you use a Regular Expression. For instance, say you'd like to break a string into sentences . A sentence can end with a period ( . ), exclamation mark ( ! ), a question mark ( ? ) or three dots ( ... ). Each of these are valid sentences, but we'd have to perform multiple splits to match all of them, if we were to use single characters or strings.
Pattern matching is where Regular Expressions excel! Let's split a string on each sentence, with any of these ending delimiters:
However, the delimiters are lost! We split on them and in the process, remove them from the output. Additionally, we have multiple whitespaces in the beginnings of the sentences, and there's an empty string in the end! This isn't to say that split() doesn't work well with Regular Expressions - but it is to say that splitting sentences out of text isn't solved well by split() . This is where we can use the match() method instead - which returns the matching patterns and their delimiters:
Note: The split() method takes in a second parameter, which specifies the limit of splitting that can occur. It doesn't alter the number of splits and elements to fit the passed argument, but rather, performs the split n times, from the start, and stops splitting after that.
To limit the number of splits we perform, we can easily supply the second argument of the split() method:
A common use case for the split() method is when someone supplies their full name as a single string:
Here, we can split the name and save it as different fields of an object to the database, for instance:
Instead of having to call get both elements using an array index, we can use array destructuring to make the assignment cleaner:
Note: The split() method doesn't support certain UTF-8 characters, such as emojis (i.e. 😄, 😍, 💗), and will replace them with a pair of �� .
- Split String into Array with Array.from()
The from() method from the Array class is the leading contender to the split() method. It's used to create an array, given a source of data - and naturally, it can be used to create an array from an iterable string :
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
The major benefit of using Array.from() instead of split() is that you don't have to bother with setting a delimiter - the constituent elements are just re-exposed and added to an array, rather than being converted explicitly. Additionally, the Array.from() method supports emoji characters:
- Split String into Array with the Spread Operator
The operator's syntax is simple and clean - and we can spread out the string into an array :
The operator also works with UTF-8 emojis:
- Split String with Object.assign()
The Object.assign() method copies all values and properties of one object - and maps them to the properties of another. In a sense - it's used for cloning objects and merging those with the same properties:
In our case - we'd be copying and mapping the values within a string onto an array:
This approach is a bit more verbose, and less aesthetically pleasing than the previous two:
It's worth noting that Object.assign() doesn't support special UTF-8 characters such as emojis:
You might also like...
Improve your dev skills!
Get tutorials, guides, and dev jobs in your inbox.
Frontend Developer & Technical Writer
In this article
React State Management with Redux and Redux-Toolkit
Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...
Getting Started with AWS in Node.js
Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!
© 2013- 2024 Stack Abuse. All rights reserved.
Table of Contents
Sometimes you have a comma-separated string and you want to convert it to an array.
A good example is if you're reading a CSV file and you want to retrieve the data as an array.
To start, let's define an example comma-separated string:
Now, we can use the built-in split method and pass it a separator, in this case, a comma, and it will take our string and turn it into an array.
That's all there is to it.
In case you want to limit how many times the separator is used, you can pass an optional second argument to the split method.
Let's say you only want the first two elements:
Alternatively, if you pass the method a blank string as the separator, it will simply split the string into individual characters.
Simply use the split method and pass it a separator and the return value will be an array.
Thanks for reading!
- Terms of Service
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.
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
Convert Array to String (with and without Commas) in JS
Last updated: Dec 31, 2022 Reading time · 4 min
# Table of Contents
- Convert Array to String (with and without Commas) using Array.join()
- Convert an array to a string without commas using String.replaceAll()
You can use the String() constructor to convert an array to a comma-separated string.
The String() constructor will return a string where the array elements are separated by commas.
The only argument we passed to the String object is the value we want to convert to a string.
Since we provided an array, the result is a comma-separated string.
The String() constructor and the Array.toString methods use the join() method to convert the array into a comma-separated string under the hood.
# Convert Array to String (with and without Commas) using Array.join()
An alternative, but also very common approach is to use the Array.join() method.
The Array.join() method will return a string where all of the array elements are joined with a comma separator.
To convert an array to a string without commas, pass an empty string to the Array.join() method.
If the separator argument is set to an empty string, the array elements are joined without any characters in between them.
The Array.join() method concatenates all of the elements in an array using a separator.
The only argument the Array.join() method takes is a separator - the string used to separate the elements of the array.
If a value for the separator argument is omitted, the array elements are joined with a comma , .
You can pass any value for the separator to the Array.join() method. Here are some other examples.
If you call the join method on an empty array, it returns an empty string.
# Working around undefined and null values
An important thing to note is that if the array contains elements that are undefined , null or an empty array  , they get converted to an empty string.
If you need to remove the null and undefined values from an array before calling the Array.join() method use the Array.filter() method.
The function we passed to the Array.filter() method gets called with each element in the array.
On each iteration, we check if the current element is not equal to null and undefined and return the result.
The filter() method returns a new array that only contains the elements that meet the condition.
The last step is to use the Array.join() method to convert the array to a comma-separated string.
# Defining a reusable function
If you have to do this often, define a reusable function.
The function takes an array as a parameter and converts the array to a comma-separated string.
You can call the join() method with an empty string to convert the array to a string without commas.
The function takes an array and optionally a separator and converts the array to a string without commas.
# Convert an array to a string without commas using String.replaceAll()
To convert an array to a string without commas:
- Use the Array.map() method to iterate over the array.
- Use the replaceAll() method to remove all commas from each array element.
- Use the Array.join() method to join the array to a string without commas.
The function we passed to the Array.map() method gets called with each element in the array.
On each iteration, we use the String.replaceAll() method to remove all commas from the string and return the result.
The map() method returns a new array containing the values returned from the callback function.
The String.replaceAll() method returns a new string with all matches of a pattern replaced by the provided replacement.
The method takes the following parameters:
The String.replaceAll() method returns a new string with the matches of the pattern replaced. The method doesn't change the original string.
The last step is to use the Array.join() method to join the array into a string without commas.
We joined the array elements without a separator, but you can use any other value.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
- Convert an Array of Objects to an Array of Values in JS
Copyright © 2024 Borislav Hadzhiev
- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- English (US)
The join() method of Array instances creates and returns a new string by concatenating all of the elements in this array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
A string to separate each pair of adjacent elements of the array. If omitted, the array elements are separated with a comma (",").
A string with all array elements joined. If array.length is 0 , the empty string is returned.
The string conversions of all array elements are joined into one string. If an element is undefined or null , it is converted to an empty string instead of the string "null" or "undefined" .
The join method is accessed internally by Array.prototype.toString() with no arguments. Overriding join of an array instance will override its toString behavior as well.
Array.prototype.join recursively converts each element, including other arrays, to strings. Because the string returned by Array.prototype.toString (which is the same as calling join() ) does not have delimiters, nested arrays look like they are flattened. You can only control the separator of the first level, while deeper levels always use the default comma.
When an array is cyclic (it contains an element that is itself), browsers avoid infinite recursion by ignoring the cyclic reference.
When used on sparse arrays , the join() method iterates empty slots as if they have the value undefined .
The join() method is generic . It only expects the this value to have a length property and integer-keyed properties.
Joining an array four different ways
The following example creates an array, a , with three elements, then joins the array four times: using the default separator, then a comma and a space, then a plus and an empty string.
Using join() on sparse arrays
join() treats empty slots the same as undefined and produces an extra separator:
Calling join() on non-array objects
The join() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length .
- Polyfill of Array.prototype.join in core-js
- Indexed collections 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
An array is a special variable, which can hold more than one value:
Why Use Arrays?
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
Creating an Array
It is a common practice to declare arrays with the const keyword.
Learn more about const with arrays in the chapter: JS Array Const .
Spaces and line breaks are not important. A declaration can span multiple lines:
You can also create an array, and then provide the elements:
The following example also creates an Array, and assigns values to it:
The two examples above do exactly the same.
There is no need to use new Array() .
For simplicity, readability and execution speed, use the array literal method.
Accessing Array Elements
You access an array element by referring to the index number :
Note: Array indexes start with 0.
 is the first element.  is the second element.
Changing an Array Element
This statement changes the value of the first element in cars :
Converting an Array to a String
Access the Full Array
Arrays are Objects
Arrays use numbers to access its "elements". In this example, person returns John:
Objects use names to access its "members". In this example, person.firstName returns John:
Array Elements Can Be Objects
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:
Array Properties and Methods
Array methods are covered in the next chapters.
The length Property
The length property of an array returns the length of an array (the number of array elements).
The length property is always one more than the highest array index.
Accessing the First Array Element
Accessing the last array element, looping array elements.
One way to loop through an array, is using a for loop:
You can also use the Array.forEach() function:
Adding Array Elements
The easiest way to add a new element to an array is using the push() method:
New element can also be added to an array using the length property:
Adding elements with high indexes can create undefined "holes" in an array:
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
After that, some array methods and properties will produce incorrect results .
The difference between arrays and objects.
Arrays are a special kind of objects, with numbered indexes.
When to Use Arrays. When to use Objects.
- You should use objects when you want the element names to be strings (text) .
- You should use arrays when you want the element names to be numbers .
But you can safely use  instead.
These two different statements both create a new empty array named points:
These two different statements both create a new array containing 6 numbers:
The new keyword can produce some unexpected results:
A Common Error
is not the same as:
How to Recognize an Array
A common question is: How do I know if a variable is an array?
The instanceof operator returns true if an object is created by a given constructor:
Complete Array Reference
For a complete Array reference, go to our:
The reference contains descriptions and examples of all Array properties and methods.
Test Yourself With Exercises
Get the value " Volvo " from the cars array.
Start the Exercise
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.
- SAP Tutorials
- Salesforce Admin
- Salesforce Developer
- Kafka Tutorial
- Spark Tutorial
- Tomcat Tutorial
- Python Tkinter
- Bash Script
- Julia Tutorial
- CouchDB Tutorial
- MongoDB Tutorial
- PostgreSQL Tutorial
- Android Compose
- Flutter Tutorial
- Kotlin Android
Web & Server
- Selenium Java
- Split Operations
- Delete Operations
- Modify Style of HTML Elements
Join elements of string array with delimiter string.
The expression to join elements of a string array arr by a delimiter string separator is
In the following example, we take a string array in arr , join the elements in the array with delimiter string ' - ' as separator, and display the resulting string in pre#output.
In the following example, we join the elements of string array arr with delimiter string '++++' as separator, and display the resulting string in pre#output.
Popular Courses by TutorialKart
App developement, web development, online tools.
- DSA with JS - Self Paced
- JS Tutorial
- JS Exercise
- JS Interview Questions
- JS Operator
- JS Projects
- JS Cheat Sheet
- JS Examples
- JS Free JS Course
- JS A to Z Guide
- JS Formatter
- JS Web Technology
- Solve Coding Problems
- How to detect the duplication of values of input fields ?
Given a 2D array, we have to convert it to a comma-separated values (CSV) string using JS.
To achieve this, we must know some array prototype functions which will be helpful in this regard:
Join function: The Array.prototype.join( ) function is used to join all the strings in an array with a character/string.
Map function: The Array.prototype.map() returns a new array with the results of calling a function that we provide, on each element.
Approach: We will use the map function and join function to combine each 1D row into a string with the separation of a comma. and then join all the individual strings with “\n”, using the join function.
Example: In this example, we will be using the map() and join() functions to convert the CSV values to strings.
Explanation: We first used the map function on the 2D array to traverse each row, then we used the join function to join the array of elements in that row using a comma. Next, that map function returns an array of strings, which we join by using “\n”. Thus resulting in a CSV string.
Alternative Approach: We can even use for loops to traverse in the array, instead of a map.
Please Login to comment...
- Web Technologies
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
Ace your Coding Interview
- DSA Problems
- Binary Tree
- Binary Search Tree
- Dynamic Programming
- Divide and Conquer
- Linked List
1. Using Array.join() function
Download Run Code
We can use any character or string as the delimiter, such as a comma (,) , a space ( ) , or a plus sign (+) . If we don’t provide any argument to the join() function, it will use the default delimiter, which is a comma (,) . Here’s an example:
2. Using Array.reduce() function
Another way to convert an array to a string using a delimiter is to use the Array.reduce() function. This is a third built-in function that executes a reducer function on each element of the array, resulting in a single output value. We can use this function to convert an array to a string by concatenating each element with a delimiter of our choice. For example, if we have an array of strings and we want to convert it to a string using a slash (/) as the delimiter, we can do this:
We can also provide an initial value for the accumulator as the second argument to the reduce() function. Here’s an example:
3. Using Array.toString() function
This is another built-in function that returns a string representing the specified array and its elements. This function is equivalent to calling the join() function without any arguments, which means it uses a comma as the default separator. For example:
4. Using Array.map() function
We can also use other functions, such as Array.map() , to join the array elements with a delimiter and perform some additional operations on them. For example, if we want to join the array elements with a space ( ) and capitalize the first letter of each element, we can use the Array.map() function like this:
Rate this post
Average rating 5 /5. Vote count: 1
No votes so far! Be the first to rate this post.
We are sorry that this post was not useful for you!
Tell us how we can improve this post?
Thanks for reading.
Like us? Refer us to your friends and support our growth. Happy coding :)
Software Engineer | Content Writer | 12+ years experience