Skip to content
Advertisement

How to target all pages after slug in JavaScript?

I’m adding classes to specific pages based on slug.

To make it more manageable, I’ve sorted of these pages into an array called darkThemePages.

However, one of the groups of pages I’m targeting are blog level 2 pages. The main blog sits on /insights. However, what I’m trying to target are all pages under this blog (i.e. /insights/*).

However, I can’t see a way to target all pages under certain slugs and if it’s possible to keep it in an array?

My approach:

JavaScript

Advertisement

Answer

You can test if a regular expression matches the pathname of the current URL, and then add/remove the class from the root element accordingly:

JavaScript

Here are some tests to show examples of what kinds of url pathnames would/wouldn’t match the regular expression:

JavaScript

And here’s a page that explains the regular expression, character by character (you can learn more there and modify/experiment as well): https://regexr.com/75plc

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement