Like the regexp in this one? What does it match?
document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|\s)MyClass(?!\S)/ , '' )
It's a negative lookahead, which means that for the expression to match, the part within (?!...) must not match. In this case the regex matches http:// only when it is not followed by the current host name (roughly, see Thilo's comment). Follow this answer to receive notifications.
A question mark ( ? ) immediately following a character means match zero or one instance of this character . This means that the regex Great!? will match Great or Great! .
The question mark and the colon after the opening parenthesis are the syntax that creates a non-capturing group. The regex Set(Value)? matches Set or SetValue. In the first case, the first (and only) capturing group remains empty. In the second case, the first capturing group matches Value.
But if you want to search a question mark, you need to “escape” the regex interpretation of the question mark. You accomplish this by putting a backslash just before the quesetion mark, like this: \? If you want to match the period character, escape it by adding a backslash before it.
?:
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
).
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