Regex that matches anything except for all whitespace

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

Leave a Comment