123
123

Reputation: 278

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

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

Upvotes: 11

Views: 21847

Answers (5)

Pranay Rana
Pranay Rana

Reputation: 176896

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");

Upvotes: 22

pmrotule
pmrotule

Reputation: 9692

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.

Upvotes: 0

Joseph
Joseph

Reputation: 119847

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
}

Upvotes: 2

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

if(!input.match(/^([\s\t\r\n]*)$/)) {
    blah.blah();
} 

Upvotes: 0

Chuck Norris
Chuck Norris

Reputation: 15190

if (!input.match(/^\s*$/)) {
    //your turn...
} 

Upvotes: 9

Related Questions