Dynamic Regular Expressions

Challenge yourself with an example that uses the RegExp object to create dynamic regular expressions to solve the problem provided in this lesson.

Benefit of strings with RegExp objects

What is the point of having an entire object dedicated to defining and using a regular expression when the literal notation alternative exists? Is this another one of those crazy quirks from JavaScript?

Actually, no, it isn’t, and we’ll explain why. The literal notation for regular expressions works great, and it is usually the one we prefer when it comes to using them. You’re probably thinking: Then why the heck did they add an alternative to what is already perfect? That is a very fine question!

Both alternatives are capable of doing exactly the same. The only benefit that the object version has over its literal counterpart comes from somewhere else: strings.

You see, the RegExp object takes its arguments as strings. And what can you do with strings? You’re correct: you can concatenate them and use ES6’s templating mechanics! And that is why this object was added to the language: because it provides developers with the ability to write dynamic expressions. In other words, you can create the RegExp during run-time using, for example, user input.

Exercise: modifying the CSS of a webpage

So, for our second exercise, let’s try to create a function that will grab the user’s selected color and modify a page CSS to replace all instances of that color for the color white. Here is the simple CSS for our page:

Get hands-on with 1200+ tech skills courses.