Reputation: 3225
I need a (javascript compliant) regex that will match any string except a string that contains only whitespace. Cases:
" " (one space) => doesn't match
" " (multiple adjacent spaces) => doesn't match
"foo" (no whitespace) => matches
"foo bar" (whitespace between non-whitespace) => matches
"foo " (trailing whitespace) => matches
" foo" (leading whitespace) => matches
" foo " (leading and trailing whitespace) => matches
Upvotes: 20
Views: 22913
Reputation:
This looks for at least one non whitespace character.
/\S/.test(" "); // false
/\S/.test(" "); // false
/\S/.test(""); // false
/\S/.test("foo"); // true
/\S/.test("foo bar"); // true
/\S/.test("foo "); // true
/\S/.test(" foo"); // true
/\S/.test(" foo "); // true
I guess I'm assuming that an empty string should be consider whitespace only.
If an empty string (which technically doesn't contain all whitespace, because it contains nothing) should pass the test, then change it to...
/\S|^$/.test(" "); // false
/\S|^$/.test(""); // true
/\S|^$/.test(" foo "); // true
Upvotes: 28
Reputation: 42099
[Am not I am]'s answer is the best:
/\S/.test("foo");
Alternatively you can do:
/[^\s]/.test("foo");
Upvotes: 2
Reputation: 41533
/^\s*\S+(\s?\S)*\s*$/
demo :
var regex = /^\s*\S+(\s?\S)*\s*$/;
var cases = [" "," ","foo","foo bar","foo "," foo"," foo "];
for(var i=0,l=cases.length;i<l;i++)
{
if(regex.test(cases[i]))
console.log(cases[i]+' matches');
else
console.log(cases[i]+' doesn\'t match');
}
working demo : http://jsfiddle.net/PNtfH/1/
Upvotes: 2
Reputation: 303205
if (myStr.replace(/\s+/g,'').length){
// has content
}
if (/\S/.test(myStr)){
// has content
}
Upvotes: 1