MagicLegend MagicLegend - 1 year ago 83
Javascript Question

JavaScript find out if url tag matches

I'm looking for a way to find out what page is currently open for a script I'm writing for the browser game TribalWars. The URL's are really similar set up, and this should be easy for somebody who know's what he's doing (which I clearly don't).

The URL looks like this:

The village ID is different for every village (duuh), so that piece should be some kind of wildcard, but the 'train' at the end is what I'm interested in. This means that the user is looking at the page I want my script to modify.

Right now I've written/found the following code:

/^\u0026.+$/ //To find the &, but it doesn't work because there is stuff in front of the &

//This piece works correctly (stole it from another script), but this will trigger at every page.

In short: I need a regex piece that can find out if the user is looking at a page from the correct domain (like the piece above) and finds out if the tag 'train' is correct.

Thanks :)

Answer Source

var str = '',
    re = /(nl|zz|en).*\.tribalwars\.(nl|net)\/game\.php(\?|.*\&)screen\=train/;

if (re.test(str)) alert('String matches');

Basically what this does is:

  • check for a prefix, either nl, zz, or en (as you provided)
  • followed by whatever
  • followed by the domain name tribalwars
  • followed by its TLD (nl or net)
  • followed by the page you are interested in /game.php
  • followed either by a ? in case screen is the first parameter, or whatever + & if it's not
  • followed by screen=train

Note that it does not matter what comes before or after the RegEx, as we are just testing without any boundary checks like ^ or $.

The last part in detail: (\?|.*\&)screen\=train - a pipe | means OR - we check either for a question mark \?, or for *any number of characters followed by an ampersand .*\&. This is useful if the parameters in your URL are organised differently

If you take a look at the URL that you provided, you will see that there are some parameters in it, after game.php. The list of parameters starts with a ? before the first argument, and after that each argument is separated from the next by &. ?village=171817&screen=train. However, the order of these parameters should not matter, therefore it is possible that the screen parameter is the first one ?screen=train&village=171817 which is then preceded by a question mark and not by an ampersand. So if screen=train is first, there's nothing between that and game.php?. If it's not first, there can be any amount of parameters before it .* followed by an ampersand and the itself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download