I have a very simple string that can contains a list which can possibly contain whitespace:
string = "one, two,three ";
I want to first split the string by ,
to create an array of three strings and then remove any whitespace using .trim()
array = string.split(',').trim();
which returns "one","two","three"
however sometimes it fails and returns an error .trim() is not a function
I read that .trim()
returns a new string not a trimmed version of the current string. So i used a for loop to do the above:
array = string.split(',');
for (var i = 0; i < array.length; i++) {
var item = array[i].trim();
array.push(item);
}
which returns "one","two","three"
my question is, can anyone explain why i was getting the error only sometimes? if the array never changed from my example and can anyone provide a cleaner solution to my fix.
TypeError: array.split is not a function
every time, so it would never ever get the error you say you are getting – Earthlysplit
method on an array. Even if you start with a string instead of an array then thesplit
method returns an array and there is notrim
method on an array. If you would push an item into the array that you are looping over, then you would never reach the end of the array, it would be an infinite loop. So, none of the code that you show would ever return anything at all. – Indifferentismarray = "one, two,three ";
- then your last piece of code will run until the browser has had enough and begs you to stop the script running – Earthlystring.split(',').trim();
returns an array so i just poorly named my example, the original var is a string as a lot of you suggest. – Starobin