Modifiers

Modifiers

Understanding Modifiers

Modifiers, also known as flags, change the behavior of a regular expression. They are added after the closing delimiter of the regular expression (e.g., /pattern/flags). Modifiers can control aspects such as case sensitivity, global matching, and multiline processing.

Common Modifiers

  1. Global (g)
    • Searches for all matches in a string, not just the first one.
javascript
	const regexGlobal = /hello/g;
	const str = 'hello world, hello universe';
	console.log(str.match(regexGlobal)); // ['hello', 'hello']
  1. Case-Insensitive (i)
    • Makes the match case-insensitive.
javascript
	const regexCaseInsensitive = /hello/i;
	console.log(regexCaseInsensitive.test('Hello')); // true (matches 'Hello' regardless of case)
	console.log(regexCaseInsensitive.test('HELLO')); // true (matches 'HELLO' regardless of case)
  1. Multiline (m)
    • Treats beginning and end characters (^ and $) as working across multiple lines (i.e., match the start or end of each line).
javascript
	const regexMultiline = /^hello/m;
	const str = 'hello world\nhello universe';
	console.log(str.match(regexMultiline)); // ['hello', 'hello']
  1. Dotall (s)
    • Allows the dot (.) to match newline characters as well.
javascript
	const regexDotall = /hello.world/s;
	console.log(regexDotall.test('hello\nworld')); // true (matches 'hello\nworld' because '.' matches newline)

Combining Modifiers

Modifiers can be combined to achieve the desired matching behavior. For example, combining the global and case-insensitive modifiers:

javascript
	const regexCombined = /hello/gi;
	const str = 'Hello world, hello universe';
	console.log(str.match(regexCombined)); // ['Hello', 'hello']

Using Modifiers in JavaScript

In JavaScript, you can use modifiers by adding them after the closing delimiter of the regex pattern or by passing them as the second argument to the RegExp constructor.

  1. Inline Modifiers
javascript
	const regexInline = /hello/gi;
	const str = 'Hello world, hello universe';
	console.log(str.match(regexInline)); // ['Hello', 'hello']
  1. RegExp Constructor
javascript
	const regexConstructor = new RegExp('hello', 'gi');
	const str = 'Hello world, hello universe';
	console.log(str.match(regexConstructor)); // ['Hello', 'hello']

Exercises

  1. Write a regular expression with the global modifier to find all occurrences of the word “JavaScript” in a string.
  2. Create a Regex pattern that matches the word “developer” in a case-insensitive manner.
  3. Write a regular expression that matches the word “start” at the beginning of each line in a multiline string.

Modifiers are essential for controlling the behavior of your Regex patterns, making them more flexible and powerful.