Navigate back to the homepage

How to use regex in typescript?

Infinitbility
TypeScript
October 31st, 2021 · 2 min read
How to use regex in typescript?

Hello Friends 👋,

Welcome To Infinitbility! ❤️

To use regex in typescript, use the new RegExp() constructor, using this you can easily create and store the regex in a variable after that you will be able to operate on it.

This tutorial will help you to use Regular expressions (RegEx) in typescript, here we will learn below three points in typescript regex.

  1. Create Regular Expressions
  2. Regular Expressions Methods
  3. Regular Expressions Practice

Let’s start today’s tutorial How to use regex in typescript?

Create Regular Expressions

There are two ways to create a regular expression in TypeScript. It can be either created with the RegExp constructor or by using forward slashes ( / ) to enclose the pattern.

Regular Expression Constructor

Syntax: new RegExp(pattern)

Example:

1const regex: RegEx = new RegExp('to');

Regular Expression Literal

Syntax: /pattern/

Example:

1const regex: RegEx = /to/;

There might also be cases where you want to create regular expressions dynamically, in which case regex literal won’t work, so you have to use a regular expression constructor.

No matter which method you choose, the result is going to be a regex object. Both regex objects will have the same methods and properties attached to them.

Regular Expressions Methods

There are mainly Five methods for testing regular expressions.

  1. RegExp.prototype.test()
  2. RegExp.prototype.exec()
  3. String.prototype.match()
  4. String.prototype.replace()
  5. String.prototype.replaceAll()

RegExp.prototype.test()

This method is used to test whether a match has been found or not. It accepts a string that we have to test against a regular expression and returns true or false depending upon if the match is found or not.

1let regex = /hello/;
2let str: string = 'hello world';
3let result: boolean = regex.test(str);
4console.log(result);
5// returns true

Output

RegExp.prototype.exec()

This method returns an array containing all the matched groups. It accepts a string that we have to test against a regular expression.

1let regex = /hello/;
2let str: string = 'hello world';
3let result: any = regex.exec(str);
4console.log(result);
5// returns [ 'hello', index: 0, input: 'hello world', groups: undefined ]

Output

String.prototype.match()

The match() method retrieves the result of matching a string against a regular expression.

let’s see an example of finding an uppercase letter using the match() method.

1const paragraph: string = 'The quick brown fox jumps over the lazy dog. It barked.';
2const regex = /[A-Z]/g;
3const found: Array<string> = paragraph.match(regex);
4
5console.log(found);
6// expected output: Array ["T", "I"]

Output

  • If you need to know if a string matches a regular expression RegExp, use RegExp.prototype.test().
  • If you only want the first match found, you might want to use RegExp.prototype.exec() instead.
  • If you want to obtain capture groups and the global flag is set, you need to use RegExp.prototype.exec() or String.prototype.matchAll() instead.

String.prototype.replace()

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If the pattern is a string, only the first occurrence will be replaced. The original string is left unchanged.

1const p: string = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
2
3console.log(p.replace(/Dog/i, 'ferret'));
4// expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"
5
6
7console.log(p.replace(/Dog/ig, 'ferret'));
8// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

Output

String.prototype.replaceAll()

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

1const p: string = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
2
3// global flag required when calling replaceAll with regex
4const regex = /Dog/ig;
5console.log(p.replaceAll(regex, 'ferret'));
6// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

The replaceAll() method is new and still, it does not support many environments so better try p.replace(/Dog/ig, 'ferret') it’s do same thing.

Regular Expressions Practice

Regex to get true or false

We have the .test() method, it will return true when the string matches or false if not.

1let str: string = "Welcome to Infinitbility";
2let regex = /to/;
3
4regex.test(str);

Output

Regex to get match value

We have the .match() method to get match content from a string.

1let str: string = "Welcome to Infinitbility";
2let regex = /to/;
3
4console.log(str.match(regex));

Output

Regex to get no of occurrence match value

Multiple times we want to know how many times the same string repeats in our data.

we have to change only regex globally like the below code example. it will provide an array of match content.

1let str: string = "Welcome to to Infinitbility";
2let regex = /to/g;
3
4console.log(str.match(regex).length);

Output

I hope it helps you, All the best 👍.

Follow me on Twitter

Join our email list and get notified about new content

No worries, I respect your privacy and I will never abuse your email.

Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.

Looking For React Native Tutorial?

we are trying to create the best Tutorial for react native developers.

When you want a daily updates about React Native Tutorial or infinitbility update subscribe to our newsletter.

Read React Native Tutorial

Request New Tutorial or Article on mail [email protected]

Guide book

Guidebook: The Javascript Monorepo Photoshop Guide

Tutorials

Categories

More articles from Infinitbility

How to check type of variable in typescript?

How to check type of variable in typescript?

Example of check datatype of variable in typescript

October 29th, 2021 · 1 min read
How to convert number to string in typescript?

How to convert number to string in typescript?

Example of number to string conversion in typescript

October 28th, 2021 · 1 min read
© 2020–2022 Infinitbility
About
Link to $https://medium.com/infinitbilityLink to $https://www.facebook.com/InfinitbilityLink to $https://github.com/infinitbilityLink to $https://twitter.com/infinitbilityLink to $https://www.buymeacoffee.com/infinitbilityLink to $mailto:[email protected]