Regular Expressions in TypeScript Regular expressions in TypeScript are supported through the built-in RegExp
object. Here are some examples of common regexp-related tasks in TypeScript.
// This tests whether a pattern matches a string.
let match = /p([a-z]+)ch/ . test ( "peach" );
console . log ( match );
// For other regexp tasks, you'll need to create a RegExp object.
let r = new RegExp ( "p([a-z]+)ch" );
// Many methods are available on these objects. Here's
// a match test like we saw earlier.
console . log ( r . test ( "peach" ));
// This finds the match for the regexp.
console . log ( "peach punch" . match ( r ));
// This also finds the first match but returns the
// start and end indexes for the match instead of the
// matching text.
let result = "peach punch" . search ( r );
console . log ( "idx:" , result );
// The `exec` method returns information about both the
// whole-pattern matches and the submatches within those matches.
let execResult = r . exec ( "peach punch" );
console . log ( execResult );
// The `matchAll` method returns an iterator of all matches
// in the input, not just the first.
let str = "peach punch pinch" ;
let matches = str . matchAll ( r );
for ( const match of matches ) {
console . log ( match );
}
// Providing a non-negative integer as the second
// argument to `match` will limit the number of matches.
console . log ( str . match ( r ));
// The `replace` method can be used to replace
// subsets of strings with other values.
console . log ( "a peach" . replace ( r , "<fruit>" ));
// The second argument to `replace` can also be a function
// that transforms the matched text.
console . log ( "a peach" . replace ( r , ( match ) => match . toUpperCase ()));
To run this TypeScript code, you would typically compile it to JavaScript first and then run it with Node.js:
$ tsc regular-expressions.ts
$ node regular-expressions.js
true
true
[ 'peach' , 'ea' , index: 0, input: 'peach punch' , groups: undefined ]
idx: 0
[ 'peach' , 'ea' , index: 0, input: 'peach punch' , groups: undefined ]
[ 'peach' , 'ea' , index: 0, input: 'peach punch pinch' , groups: undefined ]
[ 'punch' , 'un' , index: 6, input: 'peach punch pinch' , groups: undefined ]
[ 'pinch' , 'in' , index: 12, input: 'peach punch pinch' , groups: undefined ]
[ 'peach' , 'ea' , index: 0, input: 'peach punch pinch' , groups: undefined ]
a <fruit>
a PEACH
Note that TypeScript (and JavaScript) regular expressions work slightly differently from those in some other languages. They don’t have all the same methods, and some operations that are methods in other languages are implemented as string methods in TypeScript/JavaScript.
For a complete reference on TypeScript/JavaScript regular expressions, check the MDN RegExp documentation .