Router DIY — Find route match

Ran Wahle
2 min readMay 19, 2019

--

When handling the history popstate event we, of course, need to know what to do with the URL. In our case, considering the data structure we’ve put on our previous post, we actually need to go through the route data and find our match.

On our previous post, we have left a line of code calling buildRouteTree method, this method builds a route snapshot from the url, by taking it into fragments and url parameters.

How will this function work?

It contains two stages, gets the url fragments, and build a url tree from them.

Getting fragments is nothing more than a simple array splitting. We just need to take some edge cases into account, such as empty string , slash only url, url that ends with a slash and url that does not. Most of the code on that function will deal with it, the rest is just the splitting.

Getting URL Fragments

Finding the suitable route

After having the fragments from the url, we need to go through our router configuration and find the suitable route for it. We will do it by iterate through the routing configuration and check for the first suitable route.

Checking for the suitable route is done by splitting a route object into fragments and compare each fragment to the url. If there is a full match, this is our route.

Wrapping up

The essence of routing is to know what to do with the current URL, we have shown how we find a suitable route for the URL by iterating our router config, and find the suitable route configuration. Next, we are going to use the route data.

--

--