My regex is /[\w+]/g, it passes the test, however I’m not sure how it works.
I know that /\w/g passes the test because it matches all uppercase and lowercase letters and numbers.
I know that /\w+/g or /\w*/g won’t pass the test because it matches all consecutive uppercase and lowercase letters and numbers and counts them as one cluster of characters.
Why does the same regex pass the test when it’s wrapped in [box brackets]? Shouldn’t it basically do the same thing as if the brackets weren’t there? What’s going on?
I’m sorry but I don’t really understand your answer.
I know that /[\w+]/g counts (matches one) each letter individually.
I also know that /\w+/g or /\w*/g counts (matches one or more) each group, cluster or word individually.
I know what they do. I just don’t understand the difference between /\w+/g and /[\w+]/g.
For example, if we have this code:
let sentence = "This is a human.";
let regex1 = /This/;
let regex2 = /T[a-z]+s/;
let return1 = sentence.match(regex1).length;
let return2 = sentence.match(regex2).length;
Return2 ignores the [box brackets] and returns 1. It counts one group, cluster, word. In that case, why doesn’t /[\w+]/g do the same thing? What are the [box brackets] doing?
they don’t do the same thing, a character class (the one with the brackets) match one single thing, so in [\w+] the + is also a character that can be matched, here it is not a counter.
Instead in [\w]+ the + is a counter that means “one or more” of the previous thing
I get it now! Thank you.
It was unclear to me that + inside a character class behaves as a symbol and not a counter.
So everything [inside a character class] is just a symbol. And \backslash for using shorthand properties is an exception to this rule I suppose?