split (delimiter, limit)
delimiter: It is the value input by the user which specifies from which alphabet or any special symbol like “. ,; @ ? &” the String is to be split.
limit: This specifies up to how many delimiters are to be counted. Like till which point a string is to be converted into an array.
The array.split() function returns an array containing the split values.
let data = "all.files.are.in.blue.folder"; const arr = data.split(".") console.log(arr); let x = "all.files.are.in.blue.folder"; const array = x.split(".", 3) console.log(array);
[ 'all', 'files', 'are', 'in', 'blue', 'folder' ] [ 'all', 'files', 'are' ]
You can see that the split() function has converted an “all.files.are.in.blue.folder” string into an array of length 6. Here the delimiter used is “.” And hence the String is split into arrays after each “.”.
In the second example, we can see that we have added the limit in the split function parameter or argument; this precisely counts 3 delimiters which are “.” in this case, and hence only 3 values are printed in the Array.
We can also split a string by splitting from the white spaces it contains or by any specific alphabet.
The split() function checks the delimiter specified by the user and checks till the end of the String until a limit has been specified. Now you must be wondering what if a user does not input any delimiter in the String? The answer to that is that each character of the String is split into a value of an array.
let k = 'HelloWorld'; const strsplit = k.split(''); console.log(strsplit);
[ 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' ]
Converting String to an array using ArrayFrom function
The arrayLike argument specifies the String that we want to convert into an array.
[ 'J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't' ]
Converting String to an array using the spread operator
Let’s convert string to an array using the spread() operator.
let st = "hello😋" console.log([...st]);
[ 'h', 'e', 'l', 'l', 'o', '😋' ]
That’s it for this tutorial.