Understanding RegEx in JavaScript (the easy way)

Michele Riva
ITNEXT
Published in
4 min readJun 5, 2021

--

Don’t get scared by RegEx! They are easier than you think!

Photo by Caleb Minear on Unsplash

In computer science, some topics may sound scarier than others. Regular Expressions, in detail, may sound incredibly scary at first… but once you got it, you’ll find ’em incredibly easy and useful!

Why do I need RegEx?

First of all: what is a RegEx? A Regular Expression is a sequence of characters that define a search pattern.

Let’s take an example: we have a string containing both numbers and letters, and we want to delete every non-letter character.

How can we delete every number from this string? This doesn’t feel like a great solution:

Of course, the code above would work… but I think that we could do better using a simple RegEx:

That’s way easier to implement, read and test! But how does it work? In JavaScript, a RegEx can be defined in two ways:

  • Writing the RegEx between two slashes: /myregex/g
  • Using the RegExp class: const re = new Regexp("myregex", "g");

Let’s write down a couple of examples:

--

--