JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - RegExp Object

Understanding the RegExp object can significantly enhance your ability to efficiently process and manipulate text in JavaScript.

Syntax

The RegExp object can be created by using the RegExp constructor. Here's how you can use it:

let regex = new RegExp('pattern', 'flags');
  • pattern: The text pattern passed as a string in the constructor.
  • flags: Optional string containing any combination of g for global match, i for ignore case, and m for multiline matching.

Properties and Methods of RegExp Object

Property/MethodDescription
globalBoolean property that indicates whether the g flag was used.
ignoreCaseBoolean indicating whether the i flag was used.
multilineBoolean indicating whether the m flag was used.
lastIndexThe index at which to start the next match (modifiable).
sourceThe text of the pattern.
test()Tests for a match in a string. Returns true or false.
exec()Executes a search for a match in a string. Returns a result array or null.

Examples Using Various RegExp Methods

Example 1: Using test() Method

The test() method is used to test whether a pattern exists in a string or not. It returns true if the pattern matches the string, otherwise false.

Javascript
Javascript

. . . .
  • Explanation:
    • The regex /hello/i is case insensitive due to the i flag.
    • The test() method checks if "hello" exists in "Hello world!", returning true because it does, ignoring case.

Example 2: Using Flags

Using multiple flags with a regular expression to perform a global, case-insensitive search.

Javascript
Javascript

. . . .
  • Explanation:
    • The fruitPattern regex searches for "apples" globally (g) and case-insensitively (i).
    • It uses a loop with exec() to find all occurrences of "apples" in the string, showing each match and its position.

These examples illustrate the functionality of the RegExp object and its methods, which are essential for efficient text processing in JavaScript. By leveraging these methods, developers can execute complex search, validation, and text manipulation tasks effectively.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next