Template Literals 7 exercises
solution

Extracting String Pattern Matches with Template Literals

In order to extract strings with :id, use the Extract utility.

Because we're trying to match strings that contain a :, we can write our template like so:


`${string}:${string}`

This says "a string of any length, followed by a colon, followed by a string of any length."

Combining

Loading solution

Transcript

0:00 The solution here is to use extract, which is a thing we've seen before in dealing with different members of a union. Since this is a union, we want to extract the members of the union that conform to a certain pattern.

0:14 What we're looking for here, is we're looking for a template literal that we basically want to have a colon anywhere in it. That means we can have a string of any length before it and a string of any length after it.

0:27 If I remove one of these, then, now it's only going to look for colons at the very start. If I add it only to the end, then it's only going to look for colons at the very end. You can think of this like a regex really, where allowing TypeScripts to dive deep into our strings to understand all the different parts of them.

0:46 If I say, let's say, const route is DynamicRoutes here, then I'm only going to get these two options available to me. That means you can start to see that template literals can help in manipulating strings and giving powerful options to your users.