11

How can I determine if an input string only contains spaces, using javascript?

Tom Halladay
  • 5,651
  • 6
  • 46
  • 65
123
  • 278
  • 2
  • 4
  • 19
  • http://stackoverflow.com/questions/3532053/regular-expression-for-only-characters-a-z-a-z Just use search. – ayk May 10 '12 at 05:52

5 Answers5

22

Another good post for : Faster JavaScript Trim

You just need to apply trim function and check the length of the string. If the length after trimming is 0 - then the string contains only spaces.

var str = "data abc";
if((jQuery.trim( str )).length==0)
  alert("only spaces");
else 
  alert("contains other characters");
Daniel
  • 6,194
  • 7
  • 33
  • 59
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
9
if (!input.match(/^\s*$/)) {
    //your turn...
} 
Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
  • This assumes that `input` is the value, not the input element. – Joseph May 10 '12 at 05:56
  • Yeah, like `var input="dfdfd"`, I guess, getting input value from real input not a big problem. – Chuck Norris May 10 '12 at 05:57
  • I prefer this solution to .trim(), because you're looking for a specific pattern of characters, and that's precisely and explicitly what a regex describes. It would take a reader a little longer to understand your clever trick with trim. – Chris Mar 04 '16 at 18:55
2

Alternatively, you can do a test() which returns a boolean instead of an array

//assuming input is the string to test
if(/^\s*$/.test(input)){
    //has spaces
}
Joseph
  • 117,725
  • 30
  • 181
  • 234
0
if(!input.match(/^([\s\t\r\n]*)$/)) {
    blah.blah();
} 
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
0

The fastest solution is using the regex prototype function test() and looking for any character that is not a space or a line break \S :

if (/\S/.test(str))
{
    // found something other than a space or a line break
}

In case that you have a super long string, it can make a significant difference.

pmrotule
  • 9,065
  • 4
  • 50
  • 58