JavaScript RegExp

Global Objects - RegExp

RegExp :

Let us consider a scenario where we want to validate the data entered by the user in the email field. The User enters data as a string but we need to validate as email pattern. That is, a string consisting of @ and .com

To achieve this validation, we will need a powerful tool for inspecting and processing the strings having a certain pattern.

The Regular expression is a type of object in JavaScript that helps us perform this inspection and processing.

The RegExp object can be constructed using either of the two ways:

  • using RegExp constructor
  • as a literal value by enclosing within forward slash (/)
JS Object RegExp Syntax

RegExp object construction makes use of the patterns in the form of Brackets and Quantifiers.

They are the special symbols that we can put in our pattern to perform an advanced search in the given text as given in the following example.

JS Object RegExp example

Let us have a look at them and understand what they do:

Brackets help us define a pattern that enables search of a given character or a digit in a string or a number:

Brackets pattern and description

Quantifiers help us define a pattern that enables search of a set of characters or digits in a string or a number.

Quantifiers pattern and description

RegExp object has a very useful method: test().

It offers the simplest way to match the given string with the expected pattern.

It takes a parameter which is the string to be inspected against the expected pattern. When the actual pattern is compared with the expected pattern, this function returns a boolean that is either true or false. Let us consider the following code that uses RegExp to validate the given email address:

RegExp email pattern example

Additionally, we can use two string methods: search() or replace() to look for the presence of the desired pattern in a given string.

JS RegExp Example
#regexp_javascript #javascript_regex #js_regex #javascript_regex_test #javascript_regex_match #javascript_regex_example #javascript_regex_replace #js_regex_match

(New page will open, for Comment)

Not yet commented...