139

What does /\S/ mean in a regex?

while (cur ! = null) {
    if (cur.nodeType == 3 && ! /\S/. test(cur.nodeValue)) {
        element. removeChild(cur);
    } else if (cur. nodeType == 1) {
        cleanWhitespace(cur);
    }
}
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
steve
  • 1,451
  • 2
  • 9
  • 4
  • 35
    For quick reference: `\s` is a [shorthand](http://www.regular-expressions.info/shorthand.html) for `[ \t\r\n\f]`, whereas `\S` equivals to `[^ \t\r\n\f]`. – caiosm1005 Sep 19 '13 at 16:39
  • https://stackoverflow.com/a/6507078/1599699 – Andrew Dec 12 '17 at 19:54
  • 5
    The spaces between the brackets in @caiosm1005's comment are important. I lost way too much time not realizing that. – Henrik May 14 '18 at 12:44

5 Answers5

194

\s matches whitespace (spaces, tabs and new lines). \S is negated \s.

Richard H
  • 36,221
  • 37
  • 107
  • 137
76

\S matches anything but a whitespace, according to this reference.

Klaus Byskov Pedersen
  • 111,411
  • 28
  • 180
  • 220
19

I believe it means 'anything but a whitespace character'.

Spiny Norman
  • 8,152
  • 1
  • 32
  • 54
8

/\S/.test(string) returns true if and only if there's a non-space character in string. Tab and newline count as spaces.

Victor Nicollet
  • 23,969
  • 4
  • 55
  • 89
-3

The \s metacharacter matches whitespace characters.

Jason Webb
  • 7,758
  • 9
  • 39
  • 49
nick
  • 116
  • 1
  • 4