Convert String to Array JavaScript? In this article, we will discuss how to convert from String to Array javascript. In this tutorial, we try to learn a lot of examples to give you a clear and holistic view. First, we want you to understand through a method that is very close to the devjs connection, the Split () method. But first, we want you not to be confused about split (), splice (), slice () .
The Split () method syntax
1 2 |
str.split(separator, limit) |
String to Array JavaScript Using JavaScript Examples
Here is a simple example:
1 2 3 4 5 |
var fruits = 'apple, orange, pear, banana, raspberry, peach'; var ar = fruits.split(', '); // split string on comma space console.log( ar ); // [ "apple", "orange", "pear", "banana", "raspberry", "peach" ] |
No separator – str.split ();
1 2 3 4 |
var str = 'abcdefg'; var ar = str.split(); // no separator passed to split console.log( ar ); // [ "abcdefg" ] |
Empty String Separator – str.split (”);
1 2 3 4 |
var str = 'abcdefg'; var ar = str.split(''); // empty string separator console.log( ar ); // [ "a", "b", "c", "d", "e", "f", "g" ] |
Separator – str.split (‘|’);
| may be another character that needs split
1 2 3 4 |
var str = '|a|b|c|d|e|f|g|'; var ar = str.split('|'); console.log( ar ); // [ "", "a", "b", "c", "d", "e", "f", "g", "" ] |
| may be another character that needs to be split, for example “,,”
1 2 3 4 |
var str = ',,a,,b,,c,,d,,e,,f,,g,,'; var ar = str.split(',,'); console.log( ar ); // [ "", "a", "b", "c", "d", "e", "f", "g", "" ] |
The separator can be Regular Expression
1 2 3 4 5 6 7 |
var str = 'favorite desserts: brownies, banana bread, ice cream, chocolate chip cookies'; // regular expression separator var re = /:s|,s/; // split ; và , var ar = str.split(re); console.log( ar ); // [ "favorite desserts", "brownies", "banana bread", "ice cream", "chocolate chip cookies" ] |
Optional Limit Argument – limit array return
1 2 3 4 |
var str = 'abcdefg'; var ar = str.split(''); console.log( ar ); // ["a", "b", "c", "d", "e", "f", "g"] |
We can now limit the items returned in the array.
1 2 3 4 |
var str = 'abcdefg'; var ar = str.split('', 3); // chỉ lấy 3 items trong array trả về console.log( ar ); // [ "a", "b", "c" ] |
Ref: https://www.tutsmake.com/javascript-convert-string-to-array-javascript/