Skip to main content

Command Palette

Search for a command to run...

Regular Expressions in JavaScript

Published
7 min read
Regular Expressions in JavaScript

During the development cycle, many of us would have faced the situation where we need to search or replace a particular string in a larger string. Still, the search string is not a predefined set of fixed characters but it is an expression that can match multiple strings in the larger string.

Additionally, one can specify this kind of search criteria using "Regex", also known as Regular Expressions. Moreover, a regular expression can either be a single character or a series of characters.

Following are the topics in Regular Expressions

  • What are Regular Expressions in JavaScript?
  • How to define Regular Expressions in JavaScript?
  • How to evaluate Regular Expressions in JavaScript using various methods?
  • What are the different ways of writing a Regular Expression in JavaScript?

What are Regular Expressions in JavaScript?

A JavaScript Regular Expression is an object, which specifies a pattern of characters. Moreover, a typical example of a regular expression implementation is to find and replace functionality provided by all the text editors. Apart from it, one can use regex in the below scenarios:

  • First, we can split the string into multiple strings.
  • Second, we can use it to replace a particular word in the given string.
  • Thirdly, we can use it to validate text fields based on the pattern.

How to define Regular Expressions in JavaScript?

JavaScript* provides two approaches to define a regular expression object:

  • Firstly, defining a regular expression object using a regular expression literal.
  • Secondly, defining a regular expression using a regex object.

Defining a Regular Expression Object using a Regular Expression Literal:

In this approach of implementing a regular expression, the pattern comes between the forward slashes. Moreover, its syntax looks like below:

let variableName = /RegExp/

Example

  let reg=/jsworld/
  console.log(reg.test("Welcome to jsworld"))

Note: The test method validates a regex.

Defining a Regular Expression using a Regex object:

Another way of creating a regex in JavaScript is with the help of the RegExp object. Moreover, its syntax looks like below:

let variableName = new RegExp('Regex Expression')

Example

  let reg=new RegExp('jsworld')
  console.log(reg.test("Welcome to jsworld"))

What methods does JavaScript provide for evaluating a Regular Expression?

JavaScript regular expression object provides two methods: test() and exec() to evaluate a regular expression. Subsequently, let's understand the usage of both of these methods in the following sections:

How to use the test() method to evaluate a regular expression?

The "test" method evaluates the regular expression. In addition to that, it returns a boolean value based on whether the regular expression resulted in a successful result or not. Moreover, its syntax looks like below:

let variableName = /Pattern/;
variableName.test("String data")

or

let variableName = new RegExp("Pattern");
variableName.test("String data")

How to use the exec() method to evaluate a regular expression?

Similar to the "test()" method, the "exec()" method is used to evaluate the regular expression. Moreover, it returns an array of Strings based on the successful match of the regular expression. Additionally, its syntax looks like below:

let regObj = /Pattern/
regObj.exec( string );

or

let regObj = new RegExp("Pattern")
regObj.exec( string );

Example

let reg = /js/ 
console.log(reg.exec("Welcome to js world, js is used for web development"))

What are the different ways of writing a Regular Expression in JavaScript?

JavaScript provides various ways of writing regular expressions. Moreover, all these methods or techniques can be combined with each to define a unique regular expression.

How to use brackets [] to define a regular expression?

Regular expressions can use square brackets [] to define a condition for regular expressions. Additionally, its syntax looks like below:

[RegExp Conditions]

The table below shows different ways in which we can use the square brackets to define a regular expression:

image.png

Example

let reg=/[js]/; //Mathcing any one character
console.log('Matching any character available in given string')
console.log(reg.test("Welcome to js world and js is used for web development"))

reg=/[^js]/; //checking any characters is available apart from regex exp
console.log('Checking there is character in a string which is not available in regexp')
console.log(reg.test("Welcome to js world and js is used for web development"))

reg=/[a-z]/; //Matches any character from lowercase a to lowercase z
console.log('Checking given string is in lowercase letter')
console.log(reg.test("Welcome to js world and js is used for web development"))

 reg=/[A-Z]/ //Matches any character from uppercase A to uppercase Z
 console.log('Checking given string is in uppercase letter')
 console.log(reg.test("Welcome to JS world"))

 reg=/[0-9]/ //Matches any character from 0 to 9
 console.log('Checking given string is in any number')
 console.log(reg.test("Welcome to ES6"))

How to use Quantifiers to define a regular expression?

Regular expressions can use quantifiers to define a condition for regular expressions. Quantifiers provide a frequency or position of the bracketed characters.

The below table shows various usages to define a regular expression:

image.png

Example

     let reg = /E+/ // this quantifier is used to match string contains one or more E
     console.log('E+ Quantifier WELCOME TO ES6')
     console.log(reg.test("WELCOME TO ES6"))
     console.log('E+ Quantifier for String JAVASCRIPT')
     console.log(reg.test("JAVASCRIPT"))

     reg = /E*/ // this quantifier is used to match string contains zero or more E
     console.log('E* Quantifier WELCOME TO ES6')
     console.log(reg.test("WELCOME TO ES6"))
     console.log('E* Quantifier for String JAVASCRIPT')
     console.log(reg.test("JAVASCRIPT"))

     reg = /T$/ // this quantifier is used to match string contains T at end of the string
     console.log('$ Quantifier for String JAVASCRIPT')
     console.log(reg.test("JAVASCRIPT"))
     console.log('T$ Quantifier for String JS')
     console.log(reg.test("JS"))

     reg = /^T/ // this quantifier is used to match string contains  T at Starting of the string
     console.log('^T Quantifier for String TypeScript')
     console.log(reg.test("TypeScript"))
     console.log('^T Quantifier for String Script')
     console.log(reg.test("Script"))

     reg = /T?/ // this quantifier is used to match string contains  T zero or one
     console.log('T? Quantifier for String TypeScript')
     console.log(reg.test("TypeScript"))
     console.log('T? Quantifier for String JS')
     console.log(reg.test("JS"))

     reg = /T{3}/ // this quantifier is used to match string contains  T consecutively 3 times
     console.log('T{3} Quantifier for String TTTypeScript')
     console.log(reg.test("TTTypeScript"))
     console.log('T{3} Quantifier for String TypeScript')
     console.log(reg.test("TypeScript"))

     reg = /T{1,3}/ // this quantifier is used to match string contains  T consecutively 1 or 3 times
     console.log('T{1,3} Quantifier for String TTTypeScript')
     console.log(reg.test("TTTypeScript"))
     console.log('T{1,3} Quantifier for String TypeScript')
     console.log(reg.test("TypeScript"))

     reg = /T{2,}/ // this quantifier is used to match string contains  T consecutively atleast 2 times
     console.log('T{1,3} Quantifier for String TTTypeScript')
     console.log(reg.test("TTypeScript"))
     console.log('T{1,3} Quantifier for String TypeScript')
     console.log(reg.test("TypeScript"))

How to use Metacharacters to define a regular expression?

Regular expressions can use metacharacters to define a condition for regular expressions. The below table shows various usage of Metacharacters to define a regular expression:

image.png

Example

     let reg = /T..l/ // This represent a single character
     console.log('T..l Metacharacter for String JavaScriptTools')
     console.log(reg.test("JavaScriptTools"))

     reg = /\s/ //This is for white space or tab or new line
     console.log('/\s/ Metacharacter for String JavaScriptTools')
     console.log(reg.test("JavaScriptTools"))
     console.log('/\s/ Metacharacter for String JavaScript Tools')
     console.log(reg.test("JavaScript Tools"))

     reg = /\S/ //This is for non white space or tab or new line
     console.log('/\S/ Metacharacter for String JavaScriptTools')
     console.log(reg.test("JavaScriptTools"))
     console.log('/\S/ Metacharacter for String  <space> ')
     console.log(reg.test(" "))

     reg = /\d/ //This is for only digits
     console.log('/\d/ Metacharacter for String JS6')
     console.log(reg.test("JS6"))
     console.log('/\d/ Metacharacter for String  ToolsQA')
     console.log(reg.test("JS"))

     reg = /\D/ //This is for only non digits
     console.log('/\D/ Metacharacter for String 3637')
     console.log(reg.test("3637"))
     console.log('/\D/ Metacharacter for String  ToolsQA')
     console.log(reg.test("JS"))

     reg = /\w/ //This is for only alpha numeric
     console.log('/\w/ Metacharacter for String JS6')
     console.log(reg.test("JS6"))
     console.log('/\w/ Metacharacter for String  ++/;[]')
     console.log(reg.test("++/;[]"))

     reg = /\W/ //This is for only non alpha numeric
     console.log('/\w/ Metacharacter for String JS6')
     console.log(reg.test("JS6"))
     console.log('/\w/ Metacharacter for String  ++/;[]')
     console.log(reg.test("++/;[]"))

How to use Modifiers to define a regular expression?

Regular expressions can use modifiers to define a condition for regular expressions. Additionally, modifiers simplify the use of regexp by some functionalities like case sensitivity, global search, and searching in multiple lines. The below table shows various usage of Modifiers to define a regular expression:

image.png

Example

     let reg= /js/i
      console.log(" i modifiers is used to ignore case")
      console.log(reg.test("WELCOME TO JS"));

      reg  = /js/m
      console.log(" m modifer is used to match even in new line")
      console.log(reg.exec("JSTools \n i am in new line js"))

      reg = new RegExp("js","g");
      console.log(" g modifer is used to match all the string compared to expression")
      console.log(reg.exec("js6 is latest version of js"))

Key Takeaways

  • Firstly, a regular expression is a sequence of characters that define a search pattern.
  • Secondly, Regex will help to match the texts based on the pattern.
  • Thirdly, a regular expression can be defined either using literal(/) or the RegExp object.
  • Also, the Quantifier, Metacharacters, and Modifiers modify the way regular expressions are defined.
  • Additionally, we can also use them to customize the search strings.