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.
- Create Regular Expressions
- Regular Expressions Methods
- 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:
const regex: RegEx = new RegExp('to');
Regular Expression Literal
Syntax: /pattern/
Example:
const 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.
- RegExp.prototype.test()
- RegExp.prototype.exec()
- String.prototype.match()
- String.prototype.replace()
- 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.
let regex = /hello/;
let str: string = 'hello world';
let result: boolean = regex.test(str);
console.log(result);
// 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.
let regex = /hello/;
let str: string = 'hello world';
let result: any = regex.exec(str);
console.log(result);
// 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.
const paragraph: string = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found: Array<string> = paragraph.match(regex);
console.log(found);
// 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()
orString.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.
const p: string = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
console.log(p.replace(/Dog/i, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"
console.log(p.replace(/Dog/ig, 'ferret'));
// 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.
const p: string = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
// global flag required when calling replaceAll with regex
const regex = /Dog/ig;
console.log(p.replaceAll(regex, 'ferret'));
// 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.
let str: string = "Welcome to Infinitbility";
let regex = /to/;
regex.test(str);
Output
Regex to get match value
We have the .match()
method to get match content from a string.
let str: string = "Welcome to Infinitbility";
let regex = /to/;
console.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.
let str: string = "Welcome to to Infinitbility";
let regex = /to/g;
console.log(str.match(regex).length);
Output
I hope it helps you, All the best đź‘Ť.