Regex that matches anything but all spaces

I need a (javascript compatible) regular expression that will match any string except a string containing only whitespace characters. 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 
+7
source share
5 answers

It searches for at least one character without spaces.

 /\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 assume that I assume that an empty line should only consider spaces.

If an empty line (which technically does not contain all spaces, because it does not contain anything), should pass the test, and then change it to ...

 /\S|^$/.test("  ");    // false /\S|^$/.test(""); // true /\S|^$/.test(" foo "); // true 
+15
source
 /^\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/

+1
source

Try the following expression:

 /\S+/ 

\ S means any character without spaces.

+1
source
 if (myStr.replace(/\s+/g,'').length){ // has content } if (/\S/.test(myStr)){ // has content } 
0
source

[I'm not me] the best answer:

 /\S/.test("foo"); 

Alternatively, you can:

 /[^\s]/.test("foo"); 
0
source

All Articles