How to validate an exact match with Regex in TypeScript

Chris Harwell
2 min readJul 20, 2021

Regex is one of those tools you may or may not never use but nonetheless it is helpful to now.

First we need to decide what value we are matching against. In my case I am matching against an input value added

To do that I did:

const searchValue: string = event.currentTarget.value;

I chose to use event.currentTarget.value instead of event.target.value because of the following reason.

It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.

Since I needed to make a dynamic match with the Regex I created a new Regex constructor with the match and assigned it to a variable.

let exactMatch = new RegExp("\\b(" + searchValue + ")\\b","gi");

This sets a boundary rule on both sides of the searchValue variable this variable contains the value that the user types into the input value, adds the global flag to test against all possible matches and the i flag to make the search case insensitive

Lastly I checked the value of the input using

searchValue.match(exactMatch);

Since the input value is a string, I am checking that the searchValue is an exact match to the Regex rule.

This works because if you try to simply return the regex it returns the string form of the regex rules instead of the actual. Using the match method allows you to check that a string matches the Regex rules you put into place and returns an array containing all matching results.

--

--

No responses yet