JIYIK CN >

Current Location:Home > Learning > PROGRAM > TypeScript >

Regular expressions in TypeScript

Author:JIYIK Last Updated:2025/04/15 Views:

RegExpIs a regular expression used to match a fixed set of characters in a target string using TypeScript.

RegExpObjects have many properties and methods. Each property has different options when pattern matching.

Using regular expressions in TypeScript

Regex can be implemented in TypeScript in two ways. One of them is to assign a regular expression literal type RegExp.

const rExp : RegExp = /[A-C]/g;

Another way to express regular expressions is through RegExpthe constructor.

const rExp : RegExp = new RegExp("[A-C]", "g");

For the rest of this article, you will use constant regular expressions to match test strings.

Use the method in TypeScript testto check if a pattern exists in the target string

RegExpThe test method can be used booleanto check whether a specific pattern or regular expression exists in the target string by returning a variable.

const targetString : string = "All is well";
// regex to check if 'All' word is present or not.
const rExp : RegExp = /All/;
console.log(rExp.test(targetString));

Output:

true

In TypeScript, use RegExpthe string matchor execmethod to find matches in a target string.

matchThe method on a string RegExpor execthe method on a string finds matches that correspond to a regular expression in the target string.

Both methods behave similarly in finding the first match in the target string.

const targetString : string = "All is well";
const rExp : RegExp = /All/;
console.log(rExp.exec(targetString));
console.log(targetString.match(rExp))

Output:

["All"]
["All"]

The functions differ in whether they find all occurrences of a matching string or search with a global flag set.

const targetString : string = "All is well and Beautiful";
const rExp : RegExp = /[A-C]/g;
console.log(rExp.exec(targetString));
console.log(targetString.match(rExp))

Output:

["A"]
["A", "B"]

However, execthe function can also find the total number of matches in the target string corresponding to the regular expression.

function getMatches( target : string, rExp : RegExp, matches : Array<RegExpExecArray> = []) {
    const matchIfAny  = rExp.exec(target);
    matchIfAny && matches.push(matchIfAny) && getMatches(target, rExp, matches);
    return matches;
}

const rExp : RegExp = /[A-C]/g

const test_string : string = "All is Well and Beautiful";

console.log(getMatches(test_string, rExp, []).map( arr => arr[0]));

Output:

["A", "B"]

RegExpUsing flags in literal expressions in TypeScript

Some common flags in regular expressions include the ignore case flag i, the global flag g, and the multiline flag m.

The following code snippet demonstrates how to use the iand mflags.

const targetString : string = `#1 First line
#2 Second Line
#3 Third liNe`;
// regex to check  word is present or not.
const rExp1 : RegExp = /line/g;
const rExp2 : RegExp = /line/gi;
const rExp3 : RegExp = /^#\d/gi;
const rExp4 : RegExp = /^#\d/gim;
console.log(targetString.match(rExp1));
console.log(targetString.match(rExp2));
console.log(targetString.match(rExp3));
console.log(targetString.match(rExp4));

Output:

["line"]
["line", "Line", "liNe"]
["#1"]
["#1", "#2", "#3"]

Thus, ithe flag captures all occurrences line, regardless of case.

mFlags are often useful for finding patterns at the beginning and end of a line.

In this example, mthe flag is set to find all matches that begin with a digit at the beginning of a line.

Previous: None

Next:Dictionary or map type in TypeScript

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Handling exceptions with try..catch..finally in TypeScript

Publish Date:2025/04/15 Views:170 Category:TypeScript

This article will discuss try..catch..finally handling exceptions in TypeScript using the statement. Handling exceptions in TypeScript In TypeScript, try..catch..finally a block handles exceptions that occur during program runtime. It allow

Convert JSON object to a class in TypeScript

Publish Date:2025/04/15 Views:80 Category:TypeScript

Data on the internet flows in the form of strings, which can be converted into a very popular format called JSON. The JSON representation of this data usually represents an object or even a class in TypeScript. TypeScript provides the abili

Update TypeScript to the latest version using NPM

Publish Date:2025/04/15 Views:119 Category:TypeScript

This article provides a guide to update to the latest version of TypeScript using npm, which is the best and most popular method used by developers. This also gives us an in-depth look at what npm is and why to use it. Node Package Manager

Using jQuery and TypeScript

Publish Date:2025/04/15 Views:148 Category:TypeScript

This article provides the basic understanding and concepts of using jQuery with TypeScript. It guides on how to use jQuery in TypeScript through a coding example and outputs using various methods in TypeScript and provides knowledge about w

Checking for undefined in TypeScript

Publish Date:2025/04/15 Views:196 Category:TypeScript

This article will demonstrate how programmers can check for undefined in TypeScript using various coding examples and situations. It not only gives you an understanding of checking for undefined in TypeScript, but also helps in differentiat

exclude attribute in TypeScript

Publish Date:2025/04/15 Views:190 Category:TypeScript

This article will discuss excluding properties from a TypeScript type. The exclude property is used to create another type from an existing type with fewer or modified properties. Omit Exclude properties from types in TypeScript TypeScript

Function return types in TypeScript

Publish Date:2025/04/15 Views:174 Category:TypeScript

TypeScript is a strongly typed language and it is always encouraged to define the types correctly for all variables used in TypeScript. These types can help in development later, especially during debugging. In addition to variables, functi

Dictionary or map type in TypeScript

Publish Date:2025/04/15 Views:131 Category:TypeScript

Dictionaries or maps are used to quickly retrieve items from an object. TypeScript does not have any concept of maps or dictionaries. Plain JavaScript has objects that can set and retrieve key-value pairs. TypeScript provides Record types t

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial