Code question for regular expression

Tell us what’s happening:

Your code so far

I am confused on why the letter “g” is the only one able to go after the captial W??

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.63.

Challenge: Match Everything But Letters and Numbers

Link to the challenge:

Not sure if this will answer your question but g is the global flag in regex and the first test in this challenge is requiring you to use a global flag.

Basically the task is to find everything that is non-alphanumeric characters and without having /g for global search it would find the first one only and stop bug when you add global flag it will find every non-alphanumeric character in quoteSample… hope this helps

in javascript the regex itself goes between two slashes e.g.: /regex/, while you have the option of placing “flags” that can modify how javascript interprets the regex after the second slash.

One flag is g which means even after you find a match with your regex, the system will continue to find more matches until the searched string is exhausted.

So in your example, the regex is \W which matches any non-word character, and adding the g flag means instead of returning the first match, String.match() method will return an array with all matches.

Play around with regex on regex101

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.