My array:
var str=['data1,data2 '];
I have used:
var arr = str.split(",");
But one error is showed. TypeError: Object data1,data2 has no method 'split'. How can I solve this problem.
My output will be:
arr= data1,data2
// or
arr[0]=data1;
arr[1]=data2;
How can I solve this problem ?
Use the Split method when the substrings you want are separated by a known delimiting character (or characters). Regular expressions are useful when the string conforms to a fixed pattern. Use the IndexOf and Substring methods in conjunction when you don't want to extract all of the substrings in a string.
Use the str. split() method with maxsplit set to 1 to split a string only on the first space, e.g. my_str. split(' ', 1) . The split() method only performs a single split when the maxsplit argument is set to 1 .
To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.
You should do this :
var arr = str.toString().split(",");
"TypeError: Object data1,data2 has no method 'split'" indicates the variable is not considered as a string. Therefore, you must typecast it.
update 08.10.2015 I have noticed someone think the above answer is a "dirty workaround" and surprisingly this comment is upvoted. In fact it is the exact opposite - using str[0].split(",")
as 3 (!) other suggests is the real "dirty workaround". Why? Consider what would happen in these cases :
var str = [];
var str = ['data1,data2','data3,data4'];
var str = [someVariable];
str[0].split(",")
will fail utterly as soon str
holds an empty array, for some reason not is holding a String.prototype
or will give an unsatisfactory result if str
holds more than one string. Using str[0].split(",")
blindly trusting that str
always will hold 1 string exactly and never something else is bad practice. toString()
is supported by numbers, arrays, objects, booleans, dates and even functions; str[0].split()
has a huge potential of raising errors and stop further execution in the scope, and by that crashing the entire application.
If you really, really want to use str[0].split()
then at least do some minimal type checking :
var arr;
if (typeof str[0] == 'string') {
arr = str[0].split(',')
} else {
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