DEV Community

Jack Cole
Jack Cole

Posted on

9 1

Learning Regex in Javascript Part 1

Today I'll be discussing the intimidating regex. Regex, or regular expressions are a sequence of characters that are used to define a search pattern. The search pattern is most often used in string searches to find or replace certain sections of a string.

Making a Regex Object

In javascript there are two different methods to create a regex. The first is using the constructor provided by javascript, new RegExp(). Here's a quick example.

RegExp constructor

The other way is by creating a literal. Here's an example.

Literal contructor

Regex Methods

Javascript has four helpful methods that can be used with regex objects.

  • match
  • test
  • replace

Match is called on a string and takes an input of a regex object. It returns an array with any characters that matched the regex.

Test takes an input of a string and returns a boolean that indicates if the string had any matches with the regex.

Replace is used on a string, takes a regex object and a string as input and returns the new string with any sections that matched the regex replaced by the specified string.

Test cases

Brackets, Hyphens

If you use brackets around your regex you'll look for a single character. If you use a hyphen you'll look for anything in that range.

Brackets and hyphens

Flags

Flags can be added to to the end of a regex to change what is returned. In javascript the usable flags are,

  • i, ignore case
  • g, global match (find all)
  • m, multi line

Flags

Thanks for reading! Next week I'll continue to go through more complex uses of regex. The code for this lesson can be found here.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series ๐Ÿ“บ

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series ๐Ÿ‘€

Watch the Youtube series

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay