Practical Javascript 2: Trimming trailing spaces

I started JavaScript with the assumption that the string object already has a built-in function to trim preceding and proceeding spaces. Unlike C#/vb.net or T-SQL, the JavaScript string object doesn’t have this function. It’s just one of those subtle things that when religiously applied can save a few kilobytes down the wire especially in a high volume website with lots of input forms. Think of the server processing times that can be saved by performing this trimming in the browser rather than in the server-side.

I hope this turns out to be simple enough.

function TrimString(str) {

       str = str.replace(/^[ ]+(.*)$/, '$1'); // Trims leading spaces

       str = str.replace(/^(.*)[ ]+$/, '$1'); // Trims trailing spaces

       return str;

}

 

God is in the details.
-Hillman Curtis

 

Published 04-14-2009 12:21 AM by avcajipe
Filed under: ,

Comments

# re: Practical Javascript 2: Trimming trailing spaces

Tuesday, April 14, 2009 7:44 AM by smash

function trim(str) {

 var str = str.replace(/^\s\s*/, '');

 var ws = /\s/, i = str.length;

 while (ws.test(str.charAt(--i)));

 return str.slice(0, i + 1);

}

# re: Practical Javascript 2: Trimming trailing spaces

Wednesday, April 22, 2009 5:41 PM by boybawang

"...trimming in the browser rather than in the server-side"

It's still a good & recommended practice though to still trim whatever strings that need to be trimmed on the server side code. We cannot assume always that such strings were trimmed on the client.

# re: Practical Javascript 2: Trimming trailing spaces

Thursday, April 23, 2009 7:52 AM by avcajipe

Yeah, rightly so on the server too. Two trimmings are better than one.