When it comes to regex, I have a disproportionate amount of love for the lil' fella. Much like a tire iron clanking around in the trunk of your car, or a corkscrew in the back of the silverware drawer, it only truly shines when you find yourself desperately needing it. I recently found myself looking to implement a search function in a React app and would like to share how you can make one that works as snappy, effectively, and easily as mine.
The Old Way
A while ago I had an assignment that featured a search bar that utilized the classic .startsWith() method to determine which entries to display on a page.
In the background, it utilized state that was derived from a user-input search field. Using this, it compared the item description with a lowercase version of the user input (for uniformity) and then the aforementioned startsWith() to get back entries beginning with the supplied search.
And yeah sure, it works, but what if the item doesn't startsWith free? What if the people posting on Gregory's list weren't at 100% that day and they wrote dfree braun 3735 elemtric tothbrush ? Or what if the word free wasn't the first word? What then?
I could've sworn I saw a guy selling these.
The RegEx Way
Long story short, there's a way to make a better and cleaner search method, if you're willing to learn a little regex. Here's an altered version using an implementation I discovered while working on a search field for a project of my own.
And the result.
There it is!
As you'll notice, this doesn't start with "Braun" at all. As a matter of fact...
Some of this stuff ended with free. So what gives? Is regex magic?
Yes.
The .search() method in JavaScript will search through a string using a regular expression (or a string that gets converted to a regular expression) and return the index of where it finds a match, or -1 if there's no match. Hence comparing the final return to see if it is positive.
The RegExp object in JS allows you to create a new regular expression based on a string you hand it, alongside a second argument in the form of a string of optional flags. Here, I used interpolation to set the string the regular expression will look for alongside the special i flag to designate case-insensitive matching. This results in a regex equivalent of /{user search}/i.
So why not just interpolate directly inside of the .search() and save the hassle of messing around with a new Object?
Because I DO NOT recommend mucking about with back and forward slashes to make interpolation work inside a standard regex. Seriously, regex takes things very literally and $ , { , and } are all reserved characters.
/tl;dr/i
Regular Expressions are cool as heck and have lots of potential applications with searches being just the tip of the iceberg. For more information, I highly recommend RegexOne, the place I learned everything I know about RegEx.
Top comments (0)