The URLPattern web API is an URL pattern matching web-platform primitive as a generic javascript code. Also helps in controlling service worker to the subset of a site that it owns and maintains.
URLPattern() constructor accepts an Object as in input param as in the sample usage and and has test() and exec() methods.
Currently there is a partial implementation of URLPattern available in Chrome Canary under the "Experimental Web Platform features" flag.
Sample usage:
1234567891011
// Takes an Object as a param with the below optionsnewURLPattern({protocol:"https",username:"",password:"",hostname:"example.com",port:"",pathname:"/foo/bar/:image.jpg",search:"(.*)",hash:"(.*)",});
1234
// Say you want to match the pathname of `/products/(.*)`constproductsPattern=newURLPattern({"pathname":"/products/(.*)"})productsPattern.exec({"pathname":"/products/cars"}))
// Would return{"hash":{"groups":{"0":""},"input":""},"hostname":{"groups":{"0":""},"input":""},"input":{"pathname":"/products/cars"},"password":{"groups":{"0":""},"input":""},"pathname":{"groups":{"0":"cars"},"input":"/products/cars"},"port":{"groups":{"0":""},"input":""},"protocol":{"groups":{"0":""},"input":""},"search":{"groups":{"0":""},"input":""},"username":{"groups":{"0":""},"input":""}}
1234567
// imagePattern sample from the sepcconstimagePattern=newURLPattern({pathname:'/*.:imagetype(jpg|png|gif)'});if(letresult=imagePattern.exec(url)){returnhandleImage(result.pathname.groups['imagetype']);}
12345678
// apiPattern from the sepcconstapiPattern=newURLPattern({pathname:'/api/:product/:param?'});if(letresult=apiPattern.exec(url)){returnhandleAPI(result.pathname.groups['product'],result.pathname.groups['param']);}
// Service worker controlling /cars and everything under /cars/.// Does not control /carsearch.navigator.serviceWorker.register("/maps/maps-sw.js",{scope:newURLPattern({baseURL:self.location,pathname:`/cars/*?`,}),});
We also have the URLPatternList API in the proposals, that would help to do something like:
12345
// Match any URL ending with 'jpg' or 'png'.constp=newURLPatternList([{pathname:"/*.:filetype(jpg)"},{pathname:"/*.:filetype(png)"},]);
URLPattern API is highly influenced by path-to-regexp node module and support many of the features including: