Friday, October 23, 2009

Trimming with Javascript

I simple but effective implementation of javascript for trimming extra spaces from a string. A good use of it could be on form validation.
The custom trim function :
function trim (str) {
var str = str.replace(/^\s\s*/, ''),
ws = /\s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
Typical use of trim :
function validate()
val = document.getElementById("txt").value;
retval = trim12(val);

Surely if you use any rich javascript library a trim method should come with it. Have fun :)