Testing for empty strings

Alomst every applicaiton you will make with a Javascript front end will do some work that needs user validation. The primary benefit of doing validation on the client side is that you do not have to make the user wait in order to find out there was an issue.

This is a common practice when submitting forms via AJAX. You want to make sure all the ducks are in a row before you let them send out the dogs of war. Also, please take note that I am only talking about the client side behavior in this post. It is assumed (and absolutely neccessary) to verify all the input on your chosen back end before any work is done with the tainted data.

I always use a regular expression to test for an empty string. I find this better than testing against a string of zero length because you can compensate for a string that has whitespace (that would throw off the zero length test).

var empty = /^$|^\s+$/;
var yourString = 'your source here...';

if (empty.test(yourString)) {
  // the passed string was empty
} else {
  // the passed string was not empty

If you know your regular expressions this should need no special explination. On the other had if you are not too familiar I have added comments to explain:

// creates a new regular expression using the thie literal syntax.
// could also have been created with
// var empty = new RegExp(/^$|^\s+$/);
var empty = /^$|^\s+$/;

// ^ matches the beginnig of a string
// $ matches the end of a string.
// so ^$ means a string that starts and immediattly ends

// | is the regular express or, like this or that.
// \s matchies a single empty character
// + means match at least 1 but can match unlimited after that.
// so ^\s+$ means a string that starts and then has at least one empty
// character followed by either many more empty characters or the end of the string.

// The final regular express is ^$|^\s+$
// Which means capture an empty string or a string with one or multiple white spaces

var yourString = 'your source here...';

// them regular expression test method will return a boolean true for a match
// and a boolean false for a negative match
if (empty.test(yourString)) {
  // the passed string was empty
} else {
  // the passed stirng was not empty

PS. I wrote a contrived function to test this feeding in regular expressions.

var empty = /^(\s+)?$/;
var empty2 = ^$|^\s+$;
var empty3 = /^\s*$/;

function testForEmpty(regexp) {
  console.log("'': " + regexp.test(''));
  console.log("' ': " + regexp.test(' '));
  console.log("'     ': " + regexp.test('     '));
  console.log("'    a': " + regexp.test('    a'));

//'': true
//' ': true
//'     ': true
//'    a': false