156

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,738
  • 21
  • 105
  • 131
steve
  • 1,621
  • 2
  • 10
  • 4
  • 45
    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
  • 10
    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

229

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

Richard H
  • 38,037
  • 37
  • 111
  • 138
85

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

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
19

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

Spiny Norman
  • 8,277
  • 1
  • 30
  • 55
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
  • 24,361
  • 4
  • 58
  • 89
-4

The \s metacharacter matches whitespace characters.

Jason Webb
  • 7,938
  • 9
  • 40
  • 49
nick
  • 114
  • 1
  • 4