Short tip: @Trim in JavaScript

I will soon put together a longer article on how to extend the array object in JavaScript, so the @formula-lookalikes can be used as a ”native” array function. While waiting, you may like this function, that removes all empty elements in a JavaScript array.

function trim(a){ 	var tmp=new Array(); 	for(j=0;j<a.length;j++) 		if(a[j]!='') 			tmp[tmp.length]=a[j]; 	a.length=tmp.length; 	for(j=0;j<tmp.length;j++) 		a[j]=tmp[j]; 	return a; }

Can be used like this:

var a=new Array(); a[0]='Johan'; a[1]=''; a[2]='Hacker'; alert('Trimmed array is: '+trim(a));

If you just want to trim strings, you can use regular expressions (thanks Yaron Yogev!), like this:

" ab ".replace(/(^ +| +$)/, "")