I'm trying a simple string split in NodeJS, but it is returning an object, not array.
var mytext = "a,b,c,d,e,f,g,h,i,j,k";
var arr = mytext.split(",");
console.log(typeof mytext); <======= output string
console.log(typeof arr); <======= output object
jsfiddle: http://jsfiddle.net/f4NnQ/
why?
The split() method splits a string into an array of substrings. The split() method returns the new array.
As the name suggests, a Java String Split() method is used to decompose or split the invoking Java String into parts and return the Array. Each part or item of an Array is delimited by the delimiters(“”, “ ”, \\) or regular expression that we have passed. The return type of Split is an Array of type Strings.
Use the array_split() method, pass in the array you want to split and the number of splits you want to do.
The . split() method is a beneficial tool for manipulating strings. It returns a list of strings after the main string is separated by a delimiter. The method returns one or more new strings and the substrings also get returned in the list datatype.
The output of String.prototype.split
is an Array and that is an Object.
console.log(typeof []);
// object
You can confirm that the returned object is an array, like this
console.log(Object.prototype.toString.call(arr));
// [object Array]
console.log(arr);
// [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k' ]
Quoting from the MDN Documentation of String.prototype.split
,
The split() method splits a String object into an array of strings by separating the string into substrings.
Arrays are objects in javascript.
If you want to check if its an array -
you can do -
Array.isArray(arr)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With