Introduction to the RegExp Object

Learn about the RegExp object in JavaScript and look at how it is used to create regular expressions.

Why use a RegExp object?

One does not simply attempt to master regular expressions by just understanding their structure in JavaScript. We also need to understand the tools that the language itself is giving us to make use of them. This is why, in this chapter, we’ll cover the RegExp object from JavaScript along with the string methods we can also use to interact with them.

As part of the global namespace, JavaScript provides the RegExp object, which represents an instance of a regular expression. As we’ve covered in chapter 2, there is also a literal notation, which allows us to create new regular expressions directly by using their classical notation. However, there are limitations to that approach, and that is where this object comes into play. One big difference between literal and object notation is that the latter’s constructor allows for a quoted expression to be passed (without the starting and closing forward slashes), which, in turn, allows for a dynamic expression to be created (while the literal notation only allows for a constant expression).

Examples

let greeting = /[hH]ello/
let prefix = "hH"
let suffix = ""
let objGreeting = new RegExp("[" + prefix + "]ello" + suffix)
console.log(objGreeting)
//-------------------------------
let prefix1 = "bB"
let suffix1 = "w"
let objGreeting1 = new RegExp("[" + prefix1 + "]ello" + suffix1)
console.log(objGreeting1)

Check out the code from the snippet above. You can see how on the first line we’re only able to create a constant expression. However, by using the object, we can take advantage of string concatenation to create a dynamic one.

Flags as an argument

Flags are also not provided as part of the expression with the object notation. Instead, they’re passed on as a second string argument. The flags remain the same. They don’t change from one notation to the other. It’s just a matter of knowing how to provide them.