What is the importance of '/g' flag in JavaScript?


Let us understand first about regular expressions before jumping into the /g flag. A string of characters that creates a search pattern is called a regular expression. The search pattern can be applied to text replacement and search operations. A regular expression might be a simple pattern with one letter or a more complex one. Text search and replace operations of every kind can be carried out using regular expressions.

The literal notation and the constructor are the two methods for creating a RegExp object.

  • The literal notation consists of a pattern among both two slashes and optionally flags beyond the second slash. In JavaScript, you declare objects using curly brackets{}. Curly braces{} are the object literal syntax, which means that writing out a new object in this manner is known as constructing an object literal. Whenever a regular expression will remain constant, it is crucial to use literal notation. For example the usage of literal notation in loops, is not recommended.

  • A string of optional flags is the second parameter for the constructor function, which accepts otherwise a string or a RegExp object as its first parameter. The use of a constructor allows programmers to write regular expressions in JavaScript. Regex expressions are accepted by this method as function arguments in the form of Strings. As of ECMAScript 6, constructor functions now can accept literals from regular expressions. When writing regular expressions whose pattern will change as they are being executed, it is best to utilise the constructor function.

A regular expression may need to match the same string more than once on occasion. Once constructed, the regular expression object must have the /g flag set (be it via a regular expression literal, be it via the constructor RegExp). As a result, the regular expression object's property global is true, which causes a number of actions to behave differently.

Instead of terminating after the first match, JavaScript's RegExp g Modifier executes a global match, which searches for all instances of the pattern. A flag is a parameter that can be optionally added to a regex that alters how it searches. An individual lowercase alphabetic character is used to represent a flag. There are six flags in the JavaScript regex, each of which has a specific function.

We may force it to discover all matches for the pattern using the flag g, which stands for "global," rather than simply the first one.

Syntax

The JavaScript syntax for RegExp g

/regexp/g

OR

new RegExp("regexp", "g")

Example 1

In this example, the following expression parses the string, eliminates all of the digits [d], and then returns the clean string. Keep in mind that the g stands for "global," which means to search for all matches instead of just the very first.

<!DOCTYPE html> <html> <title>What is the importance of '/g' flag in JavaScript - TutorialsPoint</title> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge><meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <script> let strName = "Tutorialspoint is an online learning platform!"; let regex = /[\d]/g; document.write(strName.replace(regex, "")); </script> </body> </html>

Example 2

In this example let us understand how the match() method examines a string's compatibility with a regular expression or extracts particular strings from a string. Arrays of all matches are returned if nothing is identified, otherwise null is returned.

<!DOCTYPE html> <html> <title>What is the importance of '/g' flag in JavaScript - TutorialsPoint</title> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div id="result"></div> <script> let regularExp = /\d+/g; let strAge = "John: 42, Mike: 44"; document.getElementById("result").innerHTML =strAge.match(regularExp); </script> </body> </html>

Example 3

In this example let us understand how the split() method uses a regular expression to divide a string into an array of strings. As a delimiter to divide the string, it uses the regular expression. In the final array, the delimiters them self are not present.

<!DOCTYPE html> <html> <title>What is the importance of '/g' flag in JavaScript - TutorialsPoint</title> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div id='result'></div> <script> let regularExp = /[,:.]/; let strAge = 'John:42, Mike:44.Michael:50'; document.getElementById('result').innerHTML =strAge.split(regularExp); </script> </body> </html>

Example 4

The string argument is examined using the RegExp's exec() method to see if the regular expression's pattern is present one or more times in the string. It returns null if no match is discovered. If a match is identified, it produces an array with the full pattern's first matching string as its first element. The following example shows how to use the exec ().

Let's say you want to get authentic email addresses from a web page (this is called screen-scraping). JavaScript allows you to accomplish the following −

<!DOCTYPE html> <html> <title>What is the importance of '/g' flag in JavaScript - TutorialsPoint</title> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <script> var webPage = "<html>tutorialspoint@@test.org, tutpoint@@email.com, incorrect-emailaddress</html>"; var regExp = /[0-9a-zA-Z]+@@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+/g; do { var emailAddress = regExp.exec(webPage); document.write(emailAddress[0]+"<br>"); } while (emailAddress.index < webPage.length); </script> </body> </html>

Updated on: 04-Aug-2022

410 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements