ThomasReggi
ThomasReggi

Reputation: 59475

Javascript validation, where string is compiled of only any number of spaces

I am looking for a function that will return true / false if the string in question is complied of any number of spaces. The common method of doing this is if (string == " ") but this only works for one space. I need a function that would resolve any number of spaces to a return statement.

example

if (string == " ")
if (string == "  ")
if (string == "   ")
if (string == "    ")
if (string == "     ")

What is the best way to do this?

Upvotes: 0

Views: 214

Answers (4)

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68152

You can use a regular expression: /^ +$/.test(string).

A regular expression is also good if you want to match any whitespace rather than just spaces (which is sometimes useful): /^\s+$/.test(string). The \s matches all whitespace characters like " " and "\t". So:

/^ +$/.test("     ");// True
/^ +$/.test("   \t\t");// False
/^\s+$/.test("      ");// True
/^\s+$/.test("    \t\t");// True

For reference, "\t" will look something like

"   "

(I think SO turned the tab into spaces, but that's more or less what it would look like.)

Upvotes: 2

ChristopheCVB
ChristopheCVB

Reputation: 7315

Try :

String.prototype.count=function(s1) {
    return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}
myString.length == myString.count(' ');

Upvotes: 1

az4dan
az4dan

Reputation: 659

function check(str)
{
    for (var i = 0; i < str.length; i++)
    {
        if (str[i] != " ") return false;
    }
    return true;
}

Upvotes: 1

Erik
Erik

Reputation: 4105

You could use a simple regular expression:

var x = "    ";
if (x.match(/^ +$/)) {
  alert("yes");
} else {
  alert("no");
}

Upvotes: 3

Related Questions