views:

357

answers:

4

How to check if a user input text is all white space characters (space, tab, enter etc) in client side?

Thanks in advance!

+6  A: 

/^\s+$/.test(userText)

Change the + to * to include the empty string '' as a positive match.

Edit

More often than not though you need to trim whitespace from user-entered text and simply test if it's non-empty:

userText = userText.replace(/^\s+/, '').replace(/\s+$/, '');
if (userText === '') {
    // text was all whitespace
} else {
    // text has real content, now free of leading/trailing whitespace
}
Crescent Fresh
FWIW /^\s\s*/ is quicker than /^\s+/
J-P
Correct me if I'm wrong, but isn't the following the same as the double replace? x.replace( /^\s*(.*?)\s*$/, '$1' );
coderjoe
+1  A: 

Like this...

function isEmpty(str) {
  return str.replace(/^\s+|\s+$/g, '').length == 0;
}
Josh Stodola
A: 

If you want to see if a file contains all white space or is empty, I would recommend testing the inversion and inverting the result. That way you don't need to worry about special cases around empty string.

all whitespace is the same as no non-whitespace so:

function isWhitespaceOrEmpty(text) {
   return !/[^\s]/.test(text);
}

If you don't want empty strings you can modify it slightly:

function isWhitespaceNotEmpty(text) {
   return text.length > 0 && !/[^\s]/.test(text);
}
coderjoe
+1  A: 

This question is tagged with jQuery. In jQuery, you can run the following:

if ( $.trim( $('#myInput').val() ) == '' )
    alert('input is blank');
MacAnthony