Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like glob but for URLs, in JavaScript?

I need to match URLs against string patterns but I want to avoid RegExp to keep the patterns simple and readable.

I'd like to be able to have patterns like http://*.example.org/*, which should be equivalent of /^http:\/\/.*\.example.org\/.*$/ in RegExp. That RegExp should also illustrate why I want to keep it more readable.

Basically I'd like glob-like patterns that work for URLs. The Problem is: normal glob implementations treat / as a delimiter. That means, http://foo.example.org/bar/bla wouldn't match my simple pattern.

So, an implementation of glob that can ignore slashes would be great. Is there such a thing or something similar?

like image 802
selfawaresoup Avatar asked Jul 03 '14 15:07

selfawaresoup


2 Answers

You can start with a function like this for glob like behavior:

function glob(pattern, input) {
    var re = new RegExp(pattern.replace(/([.?+^$[\]\\(){}|\/-])/g, "\\$1").replace(/\*/g, '.*'));
    return re.test(input);
}

Then call it as:

glob('http://*.example.org/*', 'http://foo.example.org/bar/bla');
true
like image 130
anubhava Avatar answered Oct 13 '22 01:10

anubhava


Solved the problem by writing a lib for it:

https://github.com/lnwdr/calmcard

This matches arbitrary strings with simple wildcards.

like image 44
selfawaresoup Avatar answered Oct 13 '22 00:10

selfawaresoup