Like the regexp in this one? What does it match?
document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|\s)MyClass(?!\S)/ , '' )
Like the regexp in this one? What does it match?
document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|\s)MyClass(?!\S)/ , '' )
?:
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
).
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.