Using JavaScript I would like to check if a given URL matches a list of URL schemes. I have come this far:
function on_wikipedia() {
// the list of allowed locations
var allowed_locations = new Array( "http://*.wikibooks.org/*"
, "http://*.wikimedia.org/*"
, "http://*.wikipedia.org/*"
, "http://*.wikiquote.org/*"
, "http://*.wikiversity.org/*"
, "http://*.wiktionary.org/*"
, "http://www.mediawiki.org/*"
, "https://secure.wikimedia.org/*"
);
// current location; e.g. "http://en.wikipedia.org/wiki/Main_Page"
var current_location = content.document.location;
var valid = false;
// compare current_location to allowed_locations and set valid to true,
// if it matches
//
// FIXME
return valid;
}
Maybe it is a bad idea to do it like this. Maybe I should use regular expressions to make the comparason? Unfortunately I’m lost… I have no JavaScript experience at all. Could someone please point me in the right direction?
The
iat the end of the regex makes it case-insensitive. Remove if you don’t want that.In general, the regex says this:
^), look for either of the following ((?:...|...)):http://followed by either of the following, and then a literal slash (\/).+?) followed by a literal period (\.) followed bywikand then…oh, one of these domain names, followed by.org, orwww.mediawiki.orghttps://secure.wikimedia.org/Note that the very permissive
.+?allows something likehttp://foo.bar.com/?.wikibooks.org/to be matched. You probably want something more restrictive, such as letters, numbers, underscores, periods, or hyphens. If so, replace.+?with[\w.-]+?Alternatively, instead of testing against the entire URL, you might want to just check against the hostname: