0

I have a programmes page which contains tags and subcategories. On clicking a tag, the url of the page changes to something like this:

localhost:3000/programmes/global-entrances/gre?tag_id=2&url=%2Ftag_sort%2F2%3Fcategory%3Dgre

Based on which tag has been clicked I want to change the tag color, so I need to get the tag_id value from the url.

First I checked whether the url contains a string called tag_id by doing this.

$(document).ready(function(){
    var url      = window.location.href; 
    substring = "tag_id";
    if(url.indexOf(substring) > -1){
          // if true then get the tag_id value 
    }
});

Now I got stuck with it.

rrk
  • 15,677
  • 4
  • 29
  • 45
marukobotto
  • 759
  • 3
  • 12
  • 26

2 Answers2

0

Here is the shortcut to get the value of tag_id.

$(document).ready(function(){
    var url = "localhost:3000/programmes/global-entrances/gre?tag_id=2&url=%2Ftag_sort%2F2%3Fcategory%3Dgre";//window.location.href;
    var result = url.split("?")[1].split("&")[0].split("=")[1];
    alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A jsfiddle link, test it.

This is only the quick and shortcut solution, if its work for you then let me know.

Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
0

We need our good old friend RegEx for this.

First, we get the url of the page by doing document.location.href. This will give you the URL of the page, and for off-site testing purposes you can replace 'document.location.href' with the URL as a string.

The regex tests for 'tag_id=', any characters, then the ampersand which connects the next value. Then we strip 'tag_id=' from the result, and slice off the end '&' - leaving you with the value at the end.

    var url = document.location.href;
    var regEx = /(tag_id=).+?&/g;
    var value = (url.match(regEx));
    value = value[0].replace("tag_id=", "");
    value = value.slice(0, -1);
    console.log(value);
Polyducks
  • 213
  • 2
  • 13
  • I should note that this will work for urls where 'tag_id' is not the last (or only) attribute passed by the URL. – Polyducks Feb 21 '16 at 17:53