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.
In ES6 compliant runtime (i.e: node 4+) you can use use arrow function that gives you a less verbose code to achieve your goal:
> "one, two, three ".split(',').map(s => s.trim());
[ 'one', 'two', 'three' ]
split() does not work on arrays, but on strings.
As you wrote your String into an array you have to get that string via array[0], since the string is the very first Element.
If you splitted your string into an array you can call the map function and trim each value in your newly created array. like this:
array = ["one, two,three "];
array = array[0].split(',')
array = array.map(function(a){return a.trim()})
Or in short:
array = ["one, two,three "][0].split(',').map(function(a){return a.trim()})
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