Wednesday, March 26, 2008

Simple function to trim JS string arrays

Update, 08.05.08:
A better trimming-function:

function trimArray( array ){
var trimmedArray = [];

var item;
for( var i = 0, len=array.length ; i < len ; i++ ){
item = array[i];

if( item !== '' ){
trimmedArray.push( item );

return trimmedArray;

Had a case at work where I needed to make a breadcrumb-like thingy.

The breadcrumb consisted of either two or three elements, and got it's values from form-fields. Instead of checking the fields for values, I put the values in an array, trim the empty values, and join the array with a separator.

The trimming-function:

/* Trim empty strings from JS string-Arrays */
function trimStringArray( array ){
return array.join( ',' ).replace( /,{2,}/g, ',').split( ',' );

Testcode for the Firebug-console.

Result (in Firebug):