Difference between /\w/ and /\w+/ ( Regex )?

Tell us what’s happening:

Can someone tell me the difference between /\w/ and /\w+/ ?

  1. the “+” operator in regex is used for identifying repeating characters

I am confused by the usage in the example.

Your code so far


let quoteSample = "The five boxing wizards jump quickly.";
let alphabetRegexV2 = /\w/g; // Change this line
let result = quoteSample.match(alphabetRegexV2).length;

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36.

Challenge: Match All Letters and Numbers

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/regular-expressions/match-all-letters-and-numbers

\w just matches one alphanumeric character. \w+ matches one or more alphanumeric characters. Pattern matching is greedy by default, so the \w+ means “find the first alphanumeric character and then check the next character and if it is alphanumeric then include it in the match too, repeat until you run into a non-alphanumeric character.”

In the quoteSample string, \w matches the first letter (T) while \w+ matches the first word (The). The global option means to keep going through the string matching as much as you can. So /\w/g will match every non-alphanumeric in the string while /\w+/g will match every word in the string. Thus \w gives you 31 matches (for 31 alphanumeric characters in the string) while \w+ gives you six matches (for six words in the string).

10 Likes

@bbsmooth just gave a succinct explanation of the application of the regular expression you’re asking, but if you @Ashwin42 still feel you are not comfortable yet. I advise you read up the mdn documentation. Kindly visit Google and search for the keywords “mdn documentation”. I am pretty sure the first website would be the mdn’s website. Good luck on your journey

1 Like

Hi @Ashwin42 ,
I highly recommend Daniel Shiffman’s youtube tutorials for Regex. He is fun and explains the concept smoothly. I understand the whole concept after watching his videos.
There are also some “regex challenge” web pages, just google it.