Learning Regex in Javascript Part 1

123jackcole

Jack Cole

Posted on September 20, 2020

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.

💖 💪 🙅 🚩
123jackcole
Jack Cole

Posted on September 20, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related