views:

1433

answers:

6

Okay this one might be a bit tricky.

What would be the best way to check if a string contains only whitespaces?

The string is allowed to contain characters combined with whitespaces, but not only whitespaces.

+3  A: 

Just check the string against this regex:

if(mystring.match(/^\s+$/) === null) {
    alert("String is good");
} else {
    alert("String contains only whitespace");
}
Ian Clelland
This will only check whether the string contains *only* whitespace characters, but not if it contains *any* whitespaces, as was asked.
stakx
The way I read the question, is says that /any/ whitespace is allowed, as long as the string isn't /only/ whitespace. It is silent on what to do if the string is empty, so it may be that nickf's answer is still better.
Ian Clelland
+3  A: 

You could trim the string and verify the result. Unfortunately, there is no native solution in javaScript for this. You could write a function something like

return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

(See http://blog.stevenlevithan.com/archives/faster-trim-javascript for many examples)

Now you could do

if (trim(myString).length === 0) {
  // String contains only whitespace
}

You would have to create a copy of the original string first if it shouldn't be changed.

Mef
Thanks nickf... maybe I should be a little bit more careful =)
Mef
+6  A: 
if (/^\s+$/.test(myString))
{
      //string contains only whitespace
}

this checks for 1 or more whitespace characters, if you it to also match an empty string then replace + with *.

Paul Creasey
stole my answer. +1
Triptych
+1  A: 
if (!myString.replace(/^\s+|\s+$/g,""))
  alert('string is only whitespace');
shady
+9  A: 

Instead of checking the entire string to see if there's only whitespace, just check to see if there's at least one character of non whitespace:

if (/\S/.test(myString)) {
    // string is not empty and not just whitespace
}
nickf
+1 This is a better answer than mine, though perhaps not as clear when you come back a month later!
Paul Creasey
That's what comments are for :)
AntonioCS
A: 

The regular expression I ended up using for when I want to allow spaces in the middle of my string, but not at the beginning or end was this:

[\S]+(\s[\S]+)*

or

^[\S]+(\s[\S]+)*$

So, I know this is an old question, but you could do something like:

if (/^\s+$/.test(myString)) {
    //string contains characters and white spaces
}

or you can do what nickf said and use:

if (/\S/.test(myString)) {
    // string is not empty and not just whitespace
}
Will Strohmeier