JavaScript Tutorial

Javascript Regular Expression

Regular expressions are used to search and replace strings effectively. JavaScript provides the built-in RegExp type that allows us to work with regular expressions effectively.

For example, we can use regular expressions to extract useful information in web scraping like product prices. Or we can use regular expressions to validate form fields like email addresses and phone numbers.

Creating a regular expression

To create a regular expression in JavaScript, we enclose its pattern in forward-slash (/) characters or we can use RegExp constructor.

let re = /hi/;

or

let re = new RegExp('hi');

Both of the above regular expressions are the instances of the RegExp type. They match the string 'hi'.

Match regular expression

In Javascript, RegExp object has many useful methods. One of them is the test() method that allows us to test if a string contains a match of the pattern in the regular expression.

The test() method returns true if the string argument contains a match.

The following example shows how to use the test() method:-

Input:-

Output:-

Using pattern flags

Other than a pattern, a RegExp object also accepts an optional flag parameter. Flags are settings that change the searching behavior.

The ignore flag (i) -  

These expressions have many flags. For example, the ignore or i flag ignores cases when searching.

To search for a string with any cases, we use the i flag. By default, searches are case-sensitive. For example /hi/ only matches the string hi not Hi, or HI.

Input:-

Output:-

The global flag (g) -  

Global flag helps in performing a global match. It finds all matches rather than stopping after the first match.

The exec() method of the RegExp performs a search for a match in a string and returns an array that contains detailed information about the match.

Input:-

Output:-

Searching strings

It returns all matches of regexp in the string str. We use str.match(regexp) method for searching strings.

To find all matches, we use the global flag (g). And to find the matches regardless of cases, we use the ignore flag (i).

Input:-

Output:-

Replacing strings

Replace() method is used to replace the first occurrence of the string 'Ok' in the string str.

Input:-

Output:-

 

Go back to Previous Course