Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .each help, I want to trim() all the strings in an array

I'm splitting a string into an array, then I want to remove the white space around each element. I'm using jQuery. I'm able to do this successfully with 2 arrays but I know it's not correct. How do I loop thru an array and trim each element so the elements keep that change. Thanks for any tips. Here is my working code using two array. Please show me the correct way to do this.

var arVeh = vehicleText.split("|");
    var cleanArry = new Array();
    $.each(arVeh, function (idx, val) {

        cleanArry.push($.trim(this));

    });

Cheers, ~ck in San Diego

like image 284
Hcabnettek Avatar asked Dec 10 '10 16:12

Hcabnettek


People also ask

How do you trim each string in an array?

To trim all strings in an array:Use the map() method to iterate over the array and call the trim() method on each array element. The map method will return a new array, containing only strings with the whitespace from both ends removed.

What does trim function do in jquery?

trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.

How do you remove blank space in an array?

In order to remove empty elements from an array, filter() method is used. This method will return a new array with the elements that pass the condition of the callback function.


1 Answers

You don't even really need the idx or val parameters. This appears to work on jsFiddle:

var cleanVehicles = [];

$.each(vehicleText.split("|"), function(){
    cleanVehicles.push($.trim(this));
});

EDIT: Now that I've seen what you're really after, try using map:

var cleanVehicles = $.map(vehicleText.split("|"), $.trim);
like image 159
Chris Doggett Avatar answered Oct 07 '22 16:10

Chris Doggett