Something went wrong and the elves made a little mess. Some of the gifts ended up in the snow and the name tags were ruined. Fortunately, most of the letters of the names are visible. Santa Claus is convinced that the whole name can be reconstructed starting from the fragments.

The puzzle: Matching Gift Names 🎁

Today’s problem, Issue 7 of the Dev Advent Calendar 🎅 is very fast. But it requires you to use regular expressions. I still struggle to handle this aspect of JavaScript - I find it difficult even with a simple problem like this.

I begin with the solution:

The first step is to try various combinations of regex and see which one is best suited to the problem. To do this I use regex101 and do some manual tests. After identifying the right rule, I create the regular expression.

There are two ways. What I’ve used so far is like this:

It is generally the best solution because it is the most efficient. However, it assumes that you always use the same rule. This is not the case today. I need to create a different regex for each name to check. I therefore use:

Of course this code only works if I want to search for the word hello.

First I replace the # character with the . character. Why? Because the period, in the regex, indicates any single character. This way I can transform h#ello into the string h.ello. Then I’ll use h.ello in the next step.

The next step changes based on the source of the data. In our case, each name is a single word. I can therefore assume that the comparison takes place between complete strings. So I add two commands:

  • ^ indicates that the pattern is at the beginning of the string
  • $ indicates that there is nothing after the last character of the pattern.

This way I make sure that patt. only returns patty and patti but not patterson.

After finding the regex to use, all that remains is to use it. The problem is, I can’t use RegExp.prototype.test(). test() always restarts the search from the last index found. This generates bugs: without code testing I would have had a lot of trouble catching this.

Consequently I decided to use String.prototype.search(): this method always starts the search from position 0, and that’s exactly what I need.

That’s all

If you ara curious about 🎅 Dev Advent Calendar then you can follow these links: