str = str.replace(/ /g, "");

Questa toglie TUTTI gli spazi (sia all'inizio e fine che in mezzo)