0

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?

1
  • Does it need to be only spaces or would this string return true: string = " J " Commented Jul 14, 2011 at 20:57

4 Answers 4

3

You could use a simple regular expression:

var x = "    ";
if (x.match(/^ +$/)) {
  alert("yes");
} else {
  alert("no");
}
Sign up to request clarification or add additional context in comments.

3 Comments

To break that regex down for you: "^" matches the beginning of the string, " +" matches one or more space, "$" matches the end of the string.
Your way works, of course, but if you just want a true/false matches/doesn't result I'd use .test().
Yes, .test() should be slightly faster
2

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.)

Comments

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

1 Comment

I think that the str[i] syntax does not work under older versions of IE; consider using str.charAt(i) instead.
1

Try :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.