Check if a string has white space

Abs picture Abs · Nov 13, 2009 · Viewed 250.8k times · Source

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

function hasWhiteSpace(s) 
{
    var reWhiteSpace = new RegExp("/^\s+$/");

    // Check for white space
    if (reWhiteSpace.test(s)) {
        //alert("Please Check Your Fields For Spaces");
        return false;
    }

    return true;
}

By the way, I added quotes to RegExp.

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

Answer

Christian C. Salvadó picture Christian C. Salvadó · Nov 13, 2009

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.