5

Like the regexp in this one? What does it match?

document.getElementById("MyElement").className = 
   document.getElementById("MyElement").className.replace
  ( /(?:^|\s)MyClass(?!\S)/ , '' )
hugomg
  • 68,213
  • 24
  • 160
  • 246
trunpet
  • 53
  • 1
  • 3

2 Answers2

4

?: means make the capturing group a non capturing group, i.e. don't include its match as a back-reference. This is often done to increase performance and de-clutter the back-references when a capturing group is necessary to use the | operator.

In your example, it is being used to allow the or (|) of the start of the string ^ or whitespace (\s). Since the author of this code doesn't care about what it matched, they have made it a non capturing group.

?! is the negative lookahead. The regex will only match if the capturing group does not match.

In this example, the author wants to ensure the character after MyClass is not a whitespace character (\S).

It is somewhat possible the author of this code could have used word boundaries instead (\b).

alex
  • 479,566
  • 201
  • 878
  • 984
  • Basically this RE means match *word* "MyClass" anywhere, not part of the word (don't match "MyClassExt" or "ThisIsMyClass" and e.g.) – Ivan Nevostruev Nov 17 '11 at 23:11
  • What is the major difference between js regexp and regexps in other language like perl or php, I don't find the ?: and capturing group things on the tutorials provided by www.w3schools.com. – trunpet Nov 17 '11 at 23:14
  • 1
    @trunpet: You should avoid w3schools as a resource. It's outdated and full of mistakes and bad advice. – alex Nov 17 '11 at 23:34
1

The regular expression (?:^|\s) is a non-capturing group that matches either the start of the line or a whitespace character.

The regular expression (?!\S) is a negative lookahead assertion which succeeds either at the end of the string, or else when the next character is a whitespace character.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452