Url wildcard match in PluginAPI


(Joe) #1

How can I use a wildcard for url pattern matching onPageChange?

I’m trying to fire a script on all category pages and here’s what I have

api.onPageChange(url => {
	if (url === "/" || url === "/latest" || url === "/top") {
		foo();
	}
});

This works well and fires as expected. However, I would like to add category pages as well but don’t want to specify a category url.

Something like this

url === "/c/*"

to match any category page.

So how can I fix this:

api.onPageChange(url => {
	if (url === "/" || url === "/latest" || url === "/top" || url === "/c/*" ) {
		foo();
	}
});

:sweat_smile:


(Vinoth Kannan) #2

You can use JavaScript RegEx match method like below

if (url === "/" || url === "/latest" || url === "/top" || url.match(^\/c\/) ) {
  foo();
}

https://regex101.com/r/n0Xe6E/1


(Joe) #3

Thank you so much :sunflower: @vinothkannans that’s a wonderful resource.

You’re right ^\/c\/ matches correctly in the tool.

But I get a syntax error when trying to add it like so:

if (url === "/" || url === "/latest" || url === "/top" || url.match(^\/c\/) ) {
		foo();
	}
}); 

Trying it without resolves the error like so:

if (url === "/" || url === "/latest" || url === "/top" ) {
		foo();
	}
}); 

I tried to play around with it without luck :upside_down_face:

Thanks again :ok_hand:


(Vinoth Kannan) #4

Oops. I missed the wrapping slashes / in the above code. It should be url.match(/^\/c\//)


(Joe) #5

Amazing :smile::fire:

That worked like magic! :+1:

Thank you so much :sunflower: