What is regex /g meaning?

In regular expressions, the "/g" flag is a modifier that can be added to a pattern to search for all occurrences of that pattern within a given string. Here's an example to illustrate this:

Suppose you have a string "I love pizza and pasta, but pizza is my favorite". And you want to find all occurrences of the word "pizza" in the string. You can use a regular expression with the "/g" flag to do this.

Here's how the regular expression looks: /pizza/g. The "/g" flag indicates that we want to perform a global search, meaning we want to find all occurrences of the pattern within the string.

To use this regular expression in JavaScript, we can use the match() method on the string, like this:

const str = "I love pizza and pasta, but pizza is my favorite";
const pattern = /pizza/g;
const matches = str.match(pattern);
console.log(matches);

The match() method returns an array of all the matches found in the string. In this case, it will return an array containing two instances of the word "pizza".

If we didn't use the "/g" flag, the match() method would only return the first occurrence of the word "pizza" found in the string.

Here's another example code using the /g flag:

Suppose you have a string with multiple email addresses separated by commas like this: "johndoe@example.com, janedoe@example.com, bobsmith@example.com". You want to extract all the email addresses from the string and store them in an array.

To do this, you can use a regular expression with the "/g" flag. Here's how it looks:

const emailString =
  "johndoe@example.com, janedoe@example.com, bobsmith@example.com";
const emailPattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
const emailMatches = emailString.match(emailPattern);
console.log(emailMatches);

The regular expression /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g matches any valid email address in the string. The /g flag at the end of the regular expression indicates that we want to perform a global search for all matches in the string.

The match() method returns an array containing all the matches found in the string. In this case, it will return an array containing three email addresses.