Monday, September 26, 2011

Slick Javascript Trim

I found a great Trim function for Javascript that I wanted to share. Got it from http://developer.loftdigital.com/blog/trim-a-string-in-javascript and it has the cleanest explanation of space removal I've seen in a while.

My task has some form validation for incomplete fields, and it was reported back to me that users were entering a space and it was passing the validation. Now this is also why you should use both server side and client side validation so that extra space crud doesn't go into your database. But that's another post.

My javascript (inherited - I found it but didn't write it) was doing a

if (document.formname.elementname.value == "") ....

so if you enter a space, that's not equal to empty string. Validation passed, right? That syntax alone is enough reason for me to switch to JQuery. But that's out of my control

Javascript by default will use regular expressions for string comparison. If we change the if statement to read:

if (document.formname.elementname.value.replace(/^\s+|\s+$/g, '') == "")

then it will remove all spaces in the form element text no matter what. The regular expression breaks down like this:

/ start the regex
^ from the beginning
\s look for spaces
+ not just as the first character
| or (really more like also)
\s+$ look for spaces until the end of the form text
/ end regex
g = make it global

And since this is in an IF statement, it's just going to check and see what happens if you strip out all of the spaces. If you type two words separated by a space it will still go into the database as two words. and the conditional statement will still return false.

This is the cleanest and "most right" trim statement I've seen yet. Very cool!

Tuesday, September 20, 2011

Binary Fun

Today's XKCD is worth a quick read. Too funny!