tags:

views:

460

answers:

3

Hello all,

I am trying to check if a string has white space. I found this function but it doesn't seemt o be working:

 function hasWhiteSpace(s) {

  reWhiteSpace = new RegExp("/^\s+$/");
  // Check for white space
  if (reWhiteSpace.test(s)) {
  //alert("Please Check Your Fields For Spaces");
  return false;
  }
  return true;
 }

Btw, I added quotes to RegExp.

Is there something wrong? Is there anything better that I can use? Hopefully JQuery.

Thanks for any help.

+17  A: 

You can simply use the indexOf method on the input string:

function hasWhiteSpace(s) {
  return s.indexOf(' ') >= 0;
}

Or you can use the test method, on a simple RegEx:

function hasWhiteSpace(s) {
  return /\s/g.test(s);
}

This will also check for other white space characters like Tab.

CMS
Simple is so good
Zoidberg
this doesn't check for other types of white space (e.g., \t).
Bernard Chen
This is faster than a RegEx too!
Kris Walker
couldn't you put in s.indexOf(/^\s+$/) as well?
Zoidberg
Bernard: You're right, I added a regex alternative.
CMS
the s.indexOf works fine, but use '\s' instead of ' '
Bernard Chen
+1  A: 

your logic is backwards, true means false.

Brian Schroth
+2  A: 
Ian Clelland