Regular expressions is a powerful search and replace technique that you probably have used even without knowing. Be it your text editor’s “Find and Replace” feature, validation of your http request body using a third party npm module or your terminal’s ability to return list of files based on some pattern, all of them use Regular Expressions in one way or the other. It is not a concept that programmers must definitely learn but by knowing it you are able to reduce the complexity of your code in some cases.

_In this tutorial we will be learning the key concepts as well as some use cases of Regular Expressions in _javascript.

How do you write a Regular Expression?

There are two ways of writing Regular expressions in Javascript. One is by creating a **literal **and the other is using **RegExp **constructor.

//Literal
const myRegex=/cat/ig

//RegExp
const myRegex=new RegExp('cat','ig')

While both types of expressions will return the same output when tested on a particular string, the benefit of using the RegExp constructor is that it is evaluated at runtime hence allowing use of javascript variables for dynamic regular expressions. Moreover as seen in this benchmark test the RegExp constructor performs better than the literal regular expression in pattern matching.

The syntax in either type of expression consists of two parts:

  • pattern : The pattern that has to be matched in a string.
  • flags : these are modifiers which are rules that describe how pattern matching will be performed.

#regular-expressions #javascript #programming #js #regex #express

Regular Expressions: What and Why?
1.35 GEEK