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
The \S metacharacter matches non-whitespace characters. Whitespace characters can be: A space character.
Turn on free-spacing mode to ignore whitespace between regex tokens and allow # comments. Turn on free-spacing mode to ignore whitespace between regex tokens and allow # comments, both inside and outside character classes.
$ means "Match the end of the string" (the position after the last character in the string).
You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs). Search for [ \t]+$ to trim trailing 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With