- JavaScript String split()
- See Also
- Syntax
- Parameters
- Return Value
- More Examples
- Related Pages
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- How to convert a string to an array in JavaScript
- You might also like.
- Как преобразовать строку в массив js?
- 6 Ways to Convert a String to an Array in JavaScript
- 1. Using .split(‘’):
- 2. Using spread syntax ([…str])
- 3. Using Array.from(str):
- 4. Using Object.assign([], str)
- 5. Using old school method ( for loop and array.push() )
- 6. Using Array.prototype.slice.call(‘string’)
- References:
- Conclusion:
JavaScript String split()
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.
See Also
Syntax
Parameters
Parameter | Description |
separator | Optional. A string or regular expression to use for splitting. If omitted, an array with the original string is returned. |
limit | Optional. An integer that limits the number of splits. Items after the limit are excluded. |
Return Value
More Examples
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:
Related Pages
Browser Support
split() is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
How to convert a string to an array in JavaScript
There are four ways to convert a string to an array in JavaScript:
- The String.split() method uses a separator as a delimiter to split the string and returns an array.
- The Array.from() method accepts a string as input and returns a character array.
- Spread operator ( . ) from ES6 converts the string into a characters array.
- The Object.assign() method also takes the string as input and returns a character array.
Note: If you need to convert an array to a string in JavaScript, read this article.
The String.split() method converts a string into an array of substrings using a separator and returns a new array. It splits the string every time it matches against the given separator. You can also optionally pass in an integer as a second parameter to specify the number of splits. For a comma-separated string, you can convert it into an array like this:
const str = 'Apple,Orange,Mango,Cherry'; const fruits = str.split(','); console.log(fruits); // ['Apple', 'Orange', 'Mango', 'Cherry']
const str = 'Apple Orange Mango Cherry'; const fruits = str.split(' ');
If an empty string ( «» ) is used as a separator, the string is split between each character:
const str = 'apple'; const chars = str.split(''); console.log(chars); // ['a', 'p', 'p', 'l', 'e']
To limit the number of items in the array, you can pass in a second parameter to specify the number of splits. For example, let us limit our fruits list to only include the first two items:
const str = 'Apple,Orange,Mango,Cherry'; const fruits = str.split(',', 2); console.log(fruits); // ['Apple', 'Orange']
The Array.from() method creates a new Array instance from a given array or iterable object. If you pass in a string to Array.from() , it will be converted to a characters array:
const str = '🍑🍓🍉🍇🍒'; const fruits = Array.from(str); console.log(fruits); // ['🍑', '🍓', '🍉', '🍇', '🍒']
The Array.from() is part of ES6 and only works in modern browsers. However, you can use a polyfill to push the browser support way back to IE6.
const str = '🍑🍓🍉🍇🍒'; const fruits = [. str]; console.log(fruits); // ['🍑', '🍓', '🍉', '🍇', '🍒']
You can also use the Object.assign() method to convert a string into a characters array, as shown below:
const str = 'JavaScript'; const chars = Object.assign([], str); console.log(chars); // ['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']
Be careful while using Object.assign() to split a string into an array. This method copies «all enumerable own properties». This method means that it will copy all string properties to the new array.
If the string you are trying to split contains emojis, then String.split() and Object.assign() might not be the best choice. Let us look at the following example:
const str = 'Pizza 🍕'; const chars = str.split(''); console.log(chars); // [ 'P', 'i', 'z', 'z', 'a', ' ', '�', '�' ]
As you can see above, the 🍕 emoji is converted into two unknown characters. This is because the emojis are unicode characters made up of two characters. The String.split() method attempted to split up the emoji into individual characters. You should always use the Array.from() or a spread operator for strings containing emojis:
const str = 'Pizza 🍕'; const chars = [. str]; console.log(chars); // [ 'P', 'i', 'z', 'z', 'a', ' ', '🍕' ]
In this article, we looked at 4 different ways to convert a string into an array in JavaScript. If all you want to do is convert a string into an array of individual characters, you can use any of the above methods. All of them work perfectly fine and produce the same results. If you want to split a string by a specific character like a comma, dash, empty space, etc., use the String.split() method. For strings containing emojis, always use the Array.from() method or the spread operator. Read this article to learn more about JavaScript arrays and how to store multiple values in a single variable. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
Как преобразовать строку в массив js?
Для того, чтобы преобразовать строку в массив, нужно сначала определить, по какому критерию строка будет разбиваться на элементы. Например, строку можно разбить на подстроки, между которыми встречается разделитель:
const str = 'мама мыла раму'; // исходная строка const result = str.split(' '); // используем метод split с указанием разделителя // ['мама', 'мыла', 'раму']
В примере выше использовался метод split для разделения строк на элементы по определенному разделителю. Если указать в качестве разделителя пустую строку, то на выходе получим массив из символов:
// вызываем метод на строке и выводим результат console.log('test'.split('')); // => ['t', 'e', 's', 't']
Также строки имеют некоторые свойства массивов: их можно перебирать в циклах а также можно обращаться к символам через индексы:
// перебираем строку в цикле for (const symbol of 'test') console.log(symbol); > // обращение по индексу console.log('test'[1]); // => 'e'
Есть также быстрый способ разбить строку на символы с использованием рест-оператора:
const result = [. 'hello']; // ['h', 'e', 'l', 'l', 'o']; result.forEach((item) => console.log(item));
6 Ways to Convert a String to an Array in JavaScript
Arrays are the most powerful data structure in JavaScript. I found myself solving many algorithms by converting strings to arrays. So I thought of consolidating and comparing various ways to do the same. Converting from string to array is always done using the split() method but after ES6, there are many tools we could do the same. Let’s go through each method one by one and discuss the pros and cons of each.
1. Using .split(‘’):
split() is a string method that splits a string into an array of the ordered list with a pattern. This is an ES6 method and is the cleanest way to get the job done.
////* Seperate string by space character(' ') *//// const myFavShow = 'The Office'; const myFavShowArray = myFavShow.split(''); console.log(myFavShowArray) //['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e']
Another advantage of this way is we can separate strings by characters or whitespace. Below is an example of how we can do it.
////* Seperate string by whitespace(' ') *//// const myFavShow = 'The Office'; const myFavShowArray = myFavShow.split(' '); console.log(myFavShowArray) //['The', 'Office'] ////* Seperate string by a character '-' *//// const favDialogue = 'Thats-what-she-said'; const favDialogueArr = favDialogue.split('-'); console.log(favDialogueArr) //['Thats', 'what', 'she', 'said']
It also works well with Regex too. You can find the complete documentation of split() here. This way flawlessly separates the string elements into an array but it has its limitations.
NOTE: This method does not work very well with uncommon Unicode characters. This method returns the Unicode of the characters instead of actual characters which might make our job a bit more complicated(refer here) but the MDN document has been updated so that we can make it work with Unicode if we just include u flag. See here for more information.
"😄😄".split(/(?:)/); // [ "\ud83d", "\ude04", "\ud83d", "\ude04" ] "😄😄".split(/(?:)/u); // [ "😄", "😄" ]
2. Using spread syntax ([…str])
const myFavShow = 'The Office' const myFavShowArray = [. myFavShow] console.log(myFavShowArray) // ['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e']
It also helps that the limitation we have in the split() has been eliminated here. Consider the below example. We can split any characters easily using this method.
const animal = '🦊🦊' const animalArr = [. animal] console.log(animalArr) // ['🦊', '🦊']
3. Using Array.from(str):
The Array. from() method creates a new, shallow-copied Array instance from an iterable or array-like object.
const myFavShow = 'The Office' const myFavShowArray = Array.from(myFavShow); console.log(myFavShowArray) // ['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e']
const str = '😎😎' const arr = Array.from(str) console.log(arr) // ['😎', '😎']
4. Using Object.assign([], str)
The Object. assign() method copies all the properties from one or more source objects to a target object. There are two things to keep in mind about this method though. One is that Object. assign() copies property values called deep copy (Refer here to know the difference between deep copy and shallow copy). One has to keep this in mind before using this method before using it.
const myFavShow = 'The Office' const myFavShowArray = Object.assign([], myFavShow); console.log(myFavShowArray) // ['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e']
Another is that we have the same trouble as the split() method: it cannot separate uncommon characters (we see Unicode instead of actual characters).
const s = '😄😄' const a = Object.assign([], s); console.log(a) // ['\uD83D', '\uDE04', '\uD83D', '\uDE04']
5. Using old school method ( for loop and array.push() )
Although we have a lot of options to play around with, I had to mention this old-school method where we push the elements of the string using the for loopand array method push(). This is not the cleanest way of doing it but it is most definitely worth mentioning who want to stay away from the changing complexities of JavaScript (Although I would prefer other ways).
const s = 'the office'; const a = []; for (const s2 of s) a.push(s2); > console.log(a); // ['t', 'h', 'e', ' ', 'o', 'f', 'f', 'i', 'c', 'e']
const s = '𝟘𝟙𝟚𝟛😄😄'; const a = []; for (const s2 of s) a.push(s2); > console.log(a); //['𝟘', '𝟙', '𝟚', '𝟛', '😄', '😄']
6. Using Array.prototype.slice.call(‘string’)
const favShow = Array.prototype.slice.call("The Office!"); console.log(favShow); //['T', 'h', 'e', ' ', 'O', 'f', 'f', 'i', 'c', 'e', '!']
const favShow = Array.prototype.slice.call("😄😄"); console.log(favShow); //['\uD83D', '\uDE04', '\uD83D', '\uDE04']
References:
Conclusion:
To sum it all up, below are the ways we can do the job.
That’s 6 ways to convert string to array in JavaScript. Comment below if you used any other methods to get the job done.