Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
JavaScript global Property
The global property in JavaScript returns true or false depending on whether the 'g' (global) modifier is set in a regular expression pattern.
Syntax
regexPattern.global
Return Value
Returns a boolean value:
-
true- if the 'g' flag is set -
false- if the 'g' flag is not set
Example: Checking Global Flag
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Global Property</title>
</head>
<body>
<h2>JavaScript Global Property Example</h2>
<div id="result"></div>
<button onclick="checkGlobalFlag()">Check Global Flag</button>
<script>
function checkGlobalFlag() {
// Pattern with global flag
let patternWithGlobal = /random/g;
// Pattern without global flag
let patternWithoutGlobal = /random/;
let resultDiv = document.getElementById("result");
resultDiv.innerHTML =
"<p>Pattern with 'g' flag: " + patternWithGlobal.global + "</p>" +
"<p>Pattern without 'g' flag: " + patternWithoutGlobal.global + "</p>";
}
</script>
</body>
</html>
Output
When you click the button, you'll see:
Pattern with 'g' flag: true Pattern without 'g' flag: false
Example: Multiple Regex Flags
<!DOCTYPE html>
<html>
<body>
<div id="output"></div>
<script>
let patterns = [
/test/, // no flags
/test/g, // global flag
/test/gi, // global + ignore case
/test/i // ignore case only
];
let output = document.getElementById("output");
let result = "";
patterns.forEach((pattern, index) => {
result += `Pattern ${index + 1}: ${pattern} - global: ${pattern.global}<br>`;
});
output.innerHTML = result;
</script>
</body>
</html>
Output
Pattern 1: /test/ - global: false Pattern 2: /test/g - global: true Pattern 3: /test/gi - global: true Pattern 4: /test/i - global: false
Key Points
- The
globalproperty is read-only - It only checks for the 'g' flag, not other flags like 'i' or 'm'
- Global flag affects how methods like
match()andreplace()behave - With global flag, regex methods find all matches instead of just the first one
Conclusion
The global property is useful for checking whether a regular expression will match all occurrences in a string. It returns true when the 'g' flag is present, enabling global pattern matching.
Advertisements
