Updated April 3, 2023
Introduction to TypeScript RegEx
TypeScript RegEx is a Regular Expression object for matching text with some pattern. As TypeScript is also a part of JavaScript, similarly regular expressions are also the objects. TypeScript RegEx is the pattern matching standard for replacement and string parsing. These RegEx are used on various platforms and other programming environments. Since RegEx are language-independent, here, we will be discussing TypeScript RegEx. However, these Regular Expressions are now available for most of the Visual Basic and Visual Basic for Applications versions. Regular Expressions are used to find strings and replace them in a defined format. TypeScript Regular Expressions are also used to parse dates, email addresses, and urls, config files, log files, programming, or command-line scripts.
In TypeScript, Regular Expressions or RegEx object can be done in 2 ways:
- Using/ Calling a Constructor function of the Regular Expression Object.
- Using a Regular Expression Literals.
With these Regular Expression patterns, we can also use the exec and test methods of RegExp, along with methods of string-like replace, split, and search methods.
Syntax:
Here in TypeScript, we use a Constructor function of the Regular Expression Object.
let regex = new RegEx('bc*d')
Parameter: A pattern string is to be passed to the RegEx constructor object.
We can also use Literals for Regular Expressions,
let regex: RegEx = /bc*d/;
This syntax consists of any string pattern inside slashed.
Examples of TypeScript RegEx
Here are the following examples mention below
Example #1
RegEx using literals
Code:
let sampleRegEx: RegExp = /^[+ 0-9]{7}$/;
console.log(sampleRegEx.test('732g'))
// result: false
console.log(sampleRegEx.test('453gh67'))
// result: false
console.log(sampleRegEx.test('2355575'))
// result: true
console.log(sampleRegEx.test('7878734'))
// result: true
console.log(sampleRegEx.test('423%^'))
// result: false
console.log(sampleRegEx.test('abcdefg'))
// result: false
console.log(sampleRegEx.test('@#$$#%5'))
// result: false
Output:
Expression pattern [0-9] represents that the matching string should only contain numbers from 0 to 9 and only 7 digits are to be present in the string. Based on these conditions, the string checks with the expression and returns a Boolean value as true or false.
Example #2
RegEx matching for Email Address using RegEx constructor Object.
Code:
let sampleRegExMail =
new RegExp('^[a-z0-9._%+-]+@[a-z0-9-]+\.[a-z]{2,4}$');
console.log(sampleRegExMail.test('[email protected]'))
// result: true
console.log(sampleRegExMail.test('[email protected]'))
// result: false
console.log(sampleRegExMail.test('[email protected]'))
// result: true
console.log(sampleRegExMail.test('educbasample$%^.com'))
// result: false
console.log(sampleRegExMail.test('[email protected]'))
// result: true
Output:
Example #3
Replacing string value with TypeScript RegEx
Code:
var regex = /apple/gi;
var regexStr = "oranges are jucier than apple";
var newStr = regexStr.replace(regex, "mosambi");
console.log('Here is the replaced string--->', newStr)
Output:
Here, regex has a pattern ‘apple’. TypeScript Regex searches for the string ‘apple’ and replaces it with ‘mosambi’ using the string replace method and prints the complete string.
Let us get deeper on how to actually write a Regular Expression,
A TypeScript Regular Expression consists of simple characters as such, inside slashes / /. Expression such as /abcd/ or something which involves combination of special characters like /ab+c/ or complex expressions like /[a-z]+.%$\d*/.
Simple patterns are constructed of characters to find a match directly. In example 3, we had directly searched for the word ‘apple’ and replaced using the word ‘mosambi’. Such matches will be useful to search for a word, replace it, or search for a substring. Even ‘space’ counts here. There is a lot of difference between the word ‘EducbaWebsite’ and ‘Educba Website’ if we search for the expression ‘ba W’.
Coming to Special characters, when a user searches for something more than a direct match like finding more than one g’s or finding digit 5 or any special character in the pattern. For example, Finding a single r followed by zero or more a followed by a digit, the pattern looks something like this; /ra*5/ Here * refers to zero or more a’s i.e the preceding item in the pattern.
Escaping: Used for Special Characters, If the user wants to have any kind of special characters in his pattern, the user needs to escape it by using a backslash in front of a special character. For example, to search for r followed by ^ and then at, backslash ‘\’ will be used to ‘escape’ ‘^’ making it a literal instead of a special character. Pattern looks as, /r\^t/
Global Search: Alphabet ‘g’ after the end of the regular expression is used for a global search. It acts like an option or a flag that performs a whole search in the entire string and returns all the matches.
There is one more method to discuss in TypeScript RegEx, which is exec, this is used to search for a match in the specific string, returning the result of an array or a null. TypeScript RegEx objects are stateful when expressions have a global or a sticky flag set. Using exec, the user can loop over multiple matches in the input text.
Syntactically written as, regex.exec(string)
The string is the parameter passed to match the mentioned Regular Expression or the pattern. If there is a match found, exec() is a method that returns an array along with the index and the input text by further updating the last index of the object. If the matched text fails, the exec() returns null and the last index of the object is set to 0.
Example #4
TypeScript RegEx.exec()
Code:
const regexExec = RegExp('edu*', 'g');
const string = 'tutorial from educba, in the hindu education';
let arr;
while ((arr = regexExec.exec(string)) !== null) {
console.log(`Found ${arr[0]}, indexed at ${regexExec.lastIndex}.`);
// result: "Found edu. Next starts at 17."
// result: "Found edu. Next starts at 38."
}
Output:
Here we searched for string ‘edu’ globally in the string above. Have declared a while condition saying if .exec(string) is not null, then return the index of the pattern found and set the last index.
Conclusion
With this, we conclude our topic ‘TypeScript RegEx’. We have seen what is TypeScript RegEx or also known as Regular Expression. We have seen how the syntax is and how it works, pulled out a few examples using both the literal method and the constructor object method in a way that will be understandable to all of you. Also have seen what are the types of expressions, Special character escaping, global object, and many more. Thanks! Happy Learning!!
Recommended Articles
We hope that this EDUCBA information on “TypeScript RegEx” was beneficial to you. You can view EDUCBA’s recommended articles for more information.