chuck w
chuck w

Reputation: 1761

why doesn't trim() work with $.each to remove whitespaces in an array of strings

I want to use .split() to generate an array from a comma separated string, but I need to get rid of the white space.

var a = "one, two".split(",");

a  ==>  ["one", " two"]

a[1].trim() ==> "two"

$.each(a, function(i,v){v.trim()})  ==> ["one", " two"]

What am i missing about trimming whitespace from the second string in the array, and is there a better way to trim the white space from a comma separated string?

Upvotes: 0

Views: 114

Answers (5)

user1497579
user1497579

Reputation:

Your problem is that you are retrieving the value v.trim(), but doing nothing with it. Replace this portion:

$.each(a, function(i,v){v.trim()})

With this:

for(var i=0; i<a.length; i++) {
    a[i] = a[i].trim();
}

And it should work just fine.

Upvotes: 4

maethorr
maethorr

Reputation: 594

If you still want to use jquery's each do it this way:

$.each(a,function(i,v){
  a[i] = v.trim();
}

Upvotes: 1

Jacob
Jacob

Reputation: 995

your inner function doesn't actually return a value. As others have mentioned, trim returns a copy of the string with leading and trailing whitespace removed. Also, each doesn't use the return values of the functions at all, so you can't use it to replace elements. You need

$.map(a, function(v){return v.trim();});

for this to work. (Assigning to v won't work, since v is just a local variable.)

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

Just split with a regex:

var a = "one,   two,  three  ,  four".split(/\s*,\s*/);

console.log(a); //=> ["one", "two", "three", "four"]

If you have spaces at the beginning or the end you can use trim first:

a = " one,   two,  three  ,  four  ".trim().split(/\s*,\s*/);

Upvotes: 2

leonhart
leonhart

Reputation: 1201

trim() will return a trimmed string but your original won't be modified, so you have to assign to it.

Upvotes: 2

Related Questions